How to Fix: ‘x’ must be numeric in R
In this article, we are going to see how to fix: ‘x’ must be numeric. For this we will cover two example for the error message “x must be numeric”.
Example 1: Error in vector ‘x’ must be numeric
In this example, we will create a vector and try to plot a hist() plot with particular data and then occurs the ‘x’ must be numeric because we passed string data into a histogram.
How to produce an error:
R
# vector creation x <- c ( "61" , "4" , "21" , "67" , "89" , "2" ) # display vector print (x) # plotting hist hist (x) |
Output:
[1] "61" "4" "21" "67" "89" "2" Error in hist.default(x): 'x' must be numeric Traceback: 1. hist(x) 2. hist.default(x) 3. stop("'x' must be numeric")
In the above example, we have seen when we try to plot hist then it produce an error due to string data which means the histogram must be in numeric data.
How to solve this error:
To solve this error we will convert the vector elements into numeric data using as.numeric() methods.
R
x <- c ( "61" , "4" , "21" , "67" , "89" , "2" ) print (x) res <- as.numeric (x) hist (res) |
Output:
Example 2: Error in dataframe ‘x’ must be numeric
Similarly here we will create dataframe with string data elements and try to plot hist().
How to produce an error:
R
# Create data for chart val <- data.frame ( "num" = c ( "77" , "55" , "80" , "60" ), "course" = c ( 'DSA' , 'C++' , 'R' , 'Python' )) print (val) hist (val[,1]) |
Output:
num course 1 77 DSA 2 55 C++ 3 80 R 4 60 Python Error in hist.default(val[, 1]): 'x' must be numeric Traceback:
In the above example, we have seen when we try to plot hist then it produce an error due to string data which means the histogram must be in numeric data.
How to solve this error:
To solve this error we will convert the dataframe element into numeric data using as.numeric() methods.
R
# Create data for chart val <- data.frame ( "num" = c (77,55,80,60), "course" = c ( 'DSA' , 'C++' , 'R' , 'Python' )) print (val) hist (val[,1]) |
Output: