How to fix ‘x’ must be numeric in R?

The solution to this issue is to determine the data type of the variable ‘x’ and convert it to a numeric format, if it is not already numeric. To do this, you can use the as.numeric() function in R. This function will attempt to convert the value of ‘x’ to a numeric format, and if successful, the issue should be resolved.


One error you may encounter in R is:

Error in hist.default(data) : 'x' must be numeric

This error occurs when you attempt to create a histogram for a variable that is not numeric.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose we attempt to create a histogram for the following vector of data:

#define vector
data <- c('1.2', '1.4', '1.7', '1.9', '2.2', '2.5', '3', '3.4', '3.7', '4.1')

#attempt to create histogram to visualize distribution of values in vector
hist(data)

Error in hist.default(data) : 'x' must be numeric

We receive an error because data is currently not a numeric vector. We can confirm this by checking the class:

#check class
class(data)

[1] "character"

Currently data is a character vector.

How to Fix the Error

The easiest way to fix this error is to simply use as.numeric() to convert our vector to numeric:

#convert vector from character to numeric
data_numeric <- as.numeric(data)

#create histogram
hist(data_numeric)

Notice that we don’t receive an error and we’re able to successfully create the histogram because our vector is now numeric.

We can verify this by checking the class:

#check class
class(data_numeric)

[1] "numeric"

The following tutorials explain how to fix other common errors in R:

x