Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't draw Histogram, 'x' must be numeric

Tags:

r

histogram

I have a data file with this format:

Weight    Industry Type   251,787   Kellogg  h   253,9601  Kellogg  a   256,0758  Kellogg  h   .... 

I read the data and try to draw an histogram with this commands:

 ce <- read.table("file.txt", header = TRUE)   we = ce[,1]  in = ce[,2]  ty = ce[,3]  hist(we) 

But I get this error:

Error en hist.default(we) : 'x' must be numeric.

What do I need to do in order to draw histograms for my three variables ?

like image 300
José Joel. Avatar asked Feb 27 '10 22:02

José Joel.


People also ask

How do I fix x must be numeric in R?

default(X) : 'x' must be numeric. For this, we have to convert our data from character to numeric: my_data_num <- as. numeric(my_data) # Convert character to numeric my_data_num # Print first values of data # [1] -0.10 0.65 -0.71 -0.55 -1.93 1.69 -0.91 -1.02 0.28 0.30 ...

What is as numeric in R?

numeric() function in R is used to convert a character vector into a numeric vector.

How do I make a histogram in R?

Histogram can be created using the hist() function in R programming language. This function takes in a vector of values for which the histogram is plotted.


2 Answers

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

 we <- gsub(",", "", we)   # remove comma  we <- as.numeric(we)      # turn into numbers 

and now you can do

 hist(we) 

and other numeric operations.

like image 101
Dirk Eddelbuettel Avatar answered Oct 02 '22 23:10

Dirk Eddelbuettel


Note that you could as well plot directly from ce (after the comma removing) using the column name :

hist(ce$Weight) 

(As opposed to using hist(ce[1]), which would lead to the same "must be numeric" error.)

This also works for a database query result.

like image 39
Skippy le Grand Gourou Avatar answered Oct 03 '22 00:10

Skippy le Grand Gourou