【发布时间】:2020-12-28 03:02:34
【问题描述】:
我已加入两个数据表,并正在根据该数据的子集计算平均值。当下面的代码不在我编写的函数中时,它可以正常运行,但是当我尝试使用该函数时出现此错误:
Error in `[.data.table`(poll.name, AQ.Date >= Cdate & AQ.Date < Cdate + :
i evaluates to a logical vector length 159 but there are 2797432 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.
我的功能:
myfunc <- function(linked.dat, poll.name) {
linked.dat[,
`:=` (t1.avg = mean(poll.name[AQ.Date >= Cdate & AQ.Date < Cdate + 1], na.rm = TRUE),
t2.avg = mean(poll.name[AQ.Date >= Cdate + 1 & AQ.Date < Cdate + 2], na.rm = TRUE),
t3.avg = mean(poll.name[AQ.Date >= Cdate + 2 & AQ.Date <= Bdate], na.rm = TRUE),
total.avg = mean(poll.name)),
by = ID]
linked.pollname <- linked.dat
return(linked.pollname)
}
因此,在示例 df 中使用此函数如下所示:
myfunc(df, O3)
一些数据:
df <- structure(list(O3 = c(21.1, 27.3, 23.8, 29.5, 23.8, 27.1, 31.6,
25.8, 31.2, 14, 19.1, 15.5, 15.6, 28.6, 16.9, 27.4, 30.1, 24.4,
21.2, 22.1, 26.1, 19.9), AQ.Date = structure(c(3679, 3681, 3682,
3683, 3680, 3685, 3686, 3687, 3684, 3689, 3673, 3675, 3677, 3678,
3686, 3687, 3688, 3692, 3681, 3693, 3695, 3696), class = "Date"),
ID = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
"a", "a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"
), Cdate = structure(c(3673, 3673, 3673, 3673, 3673,
3673, 3673, 3673, 3673, 3673, 3673, 3673, 3677, 3677, 3677,
3677, 3677, 3677, 3677, 3677, 3677, 3677), class = "Date"),
Bdate = structure(c(3690, 3690, 3690, 3690, 3690, 3690,
3690, 3690, 3690, 3690, 3690, 3690, 3696, 3696, 3696, 3696,
3696, 3696, 3696, 3696, 3696, 3696), class = "Date"), Total_weeks = c(2.428571,
2.428571, 2.428571, 2.428571, 2.428571, 2.428571, 2.428571,
2.428571, 2.428571, 2.428571, 2.428571, 2.428571, 2.714286,
2.714286, 2.714286, 2.714286, 2.714286, 2.714286, 2.714286,
2.714286, 2.714286, 2.714286)), row.names = c(NA, -22L), class = "data.frame")
setDT(df)
我不明白这个错误是什么意思。回收指的是什么?为什么它只发生在函数内?如何调整功能以解决错误?
【问题讨论】:
-
在不知道您的数据是什么样子的情况下,很难就这个问题为您提供具体的帮助。请让这个问题可重现。这包括样本明确数据(例如,
dput(head(x))或data.frame(x=...,y=...)),可能还有给定输入的预期输出。参考:stackoverflow.com/q/5963269、minimal reproducible example 和 stackoverflow.com/tags/r/info。谢谢! -
您的问题的一个问题(可能是一般问题)是您对
myfunc的调用有一个O3的符号,R 试图解决这个问题。就我而言,它什么也没找到,因此很快就会出现找不到对象的错误。但是,如果您在调用(或父)框架中有一个名为O3的对象,那么您所做的比我认为您打算做的要多得多。如果我改为使用myfunc(df, "O3"),则会收到错误fastmean was passed type character, not numeric or logical(data.table的东西),这表明您使用O3符号是为了在df内解析。 -
您似乎更多地尝试进行非标准评估,但在
data.table构造之外,这不起作用。 -
查看我的答案的编辑,我怀疑如果不够的话它更接近。