Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R using diff: non-numeric argument to binary operator error

Tags:

types

r

We parse a CSV-File with some numbers with the following command:

tt <- read.table("test2.csv",sep=";",stringsAsFactors=FALSE)

And it works. Printingtt[1,] yields a nice vector and sd(tt[1,]) is sensible.

However, when we try

diff(tt[1,])

The command-line returns the error:

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :
    non-numeric argument to binary operator error

Why is that? Any ideas?

like image 988
Joachim Avatar asked Aug 25 '14 02:08

Joachim


People also ask

What does it mean non-numeric argument to binary operator?

The “non-numeric argument to binary operator” error occurs when we perform arithmetic operations on non-numeric elements.

How do I convert non-numeric to numeric in R?

To convert factors to the numeric value in R, use the as. numeric() function. If the input is a vector, then use the factor() method to convert it into the factor and then use the as. numeric() method to convert the factor into numeric values.

What is a binary operator in R?

Most of the operators that we use in R are binary operators (having two operands). Hence, they are infix operators, used between the operands. Actually, these operators do a function call in the background.


1 Answers

I presume that in your tt[1,], that

class(tt[1,])
# [1] "data.frame"

So if you use as.numeric, you should be okay. Try this:

diff(as.numeric(tt[1,]))

Here's an example that we can inspect:

tt <- data.frame(x = 1, y = 2)
is.vector(tt[1,])
# [1] FALSE
class(tt[1,])
# [1] "data.frame"
diff(tt[1,])
# Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] : 
#   non-numeric argument to binary operator
as.numeric(tt[1,])
# [1] 1 2
diff(as.numeric(tt[1,]))
# [1] 1
like image 188
Rich Scriven Avatar answered Oct 18 '22 22:10

Rich Scriven