R Error in correlation test. 'x' must be a numeric vector

tom sawyer picture tom sawyer · Apr 19, 2017 · Viewed 9.9k times · Source

I know that this question has been asked before but not in the context i am asking it now.

I have a dataframe that looks like this

      year    Units   
1 2005-2007   0.082 
2 2008-2010   0.411 
3 2011-2013   1.258 

my simple code looks like this

Year = mydata$year
Units = mydata$Units
cor.test(mydataRyear, mydata$Units, type=pearson)

when i run the code i get the error

Error in cor.test.default(mydata$year, mydata$Units, type = pearson) : 'x' must be a numeric vector

your comments and suggestions are highly welcomed

Answer

Andrew Gustar picture Andrew Gustar · Apr 19, 2017

year is not a numeric value - it will be either a character string or a factor. Check with str(mydata).

You could turn it into a numeric value by e.g. as.numeric(substr(mydata$year,1,4)) or by using the factor levels as.numeric(as.factor(mydata$year)) - although check the ordering makes sense if you use the latter.