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?
The “non-numeric argument to binary operator” error occurs when we perform arithmetic operations on non-numeric elements.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With