How to Fix in R: ‘x’ must be numeric


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"

Additional Resources

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

How to Fix: NAs Introduced by Coercion
How to Fix: incorrect number of subscripts on matrix
How to Fix: number of items to replace is not a multiple of replacement length

Leave a Reply

Your email address will not be published. Required fields are marked *