以下是我想要做的事情的要点:
我有2个数据框:
x(id是唯一的)
id timestamp
282462839 2012-12-05 10:55:00
282462992 2012-12-05 12:08:00
282462740 2012-12-05 12:13:00
282462999 2012-12-05 12:48:00
y(id不是唯一的)
id value1 value2
282462839 300 100
282462839 300 200
282462839 400 300
282462999 500 400
282462999 300 150
我还有一个函数myfunc(id,pvalue),它计算一些东西,并根据pvalue和其他value1s返回一个value2值(比pvalue == value1更复杂)
我想为x创建第3列,其中包含相应的计算myfunc(id,pvalue),其中pvalue是一个常量的整数(比如20)。
所以从本质上讲,我想这样做:
x$t20 <- myfunc(x$id,20)
我试着这样使用lappy和sapply:
x$t20 <- sapply(as.vector(x$id),myfunc,pvalue=20)
我尝试使用lapply并且没有as.vector,但我一直收到此错误:
Error in .pointsToMatrix(p2) : Wrong length for a vector, should be 2
当我只是在$ t20中复制$ id时,它会起作用。
我该怎么做?
编辑1: 这是myfunc的骨架:
myfunc <- function(xid,pvalue) {
result <- subset(y,id==xid)
retVal <- -1
if(nrow(result) < 12){
return(NaN)
}
for(i in (1:nrow(result))){
#code to process result
}
return(retVal)
}
答案 0 :(得分:1)
如果没有完整的代码,很难提供帮助,但这里有一些提示。首先,您可以获取应该处理的id的逻辑向量,然后使用向量化的ifelse
语句。
tmp <- table(y$id) >= 12
y$t20 <- ifelse(tmp[as.character(y$id)], your_new_func(), NaN)