使用diff:非数字参数到二元运算符错误。

时间:2021-07-25 09:25:40

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

我们使用以下命令解析一个带有一些数字的csv文件:

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

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

和它的工作原理。Printingtt[1,]产生一个好的矢量和sd(tt[1,])是合理的。

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?

这是为什么呢?什么好主意吗?

2 个解决方案

#1


5  

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

我认为在你的tt[1]中。

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

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

如果你用as。数字,你应该没问题。试试这个:

> 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

#2


0  

This also works:

这同样适用:

for (i1 in 1:length(dat.diff))
{
diffy <- diff(as.numeric(dat.diff[,i1]))
dat.diff[,i1] <- c(diffy, NA)
}

#1


5  

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

我认为在你的tt[1]中。

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

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

如果你用as。数字,你应该没问题。试试这个:

> 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

#2


0  

This also works:

这同样适用:

for (i1 in 1:length(dat.diff))
{
diffy <- diff(as.numeric(dat.diff[,i1]))
dat.diff[,i1] <- c(diffy, NA)
}