我试图让匿名函数返回多列j
的论证data.table
。这是一个例子:
## sample data
tmpdt <- data.table(a = c(rep("a", 5), rep("b", 5)),
b = c(rep("f", 3), rep("r", 7)),
c = 1:10,
d = 21:30)
tmpdt[c %in% c(2,4), c := NA]
## this works fine
tmpdt[ , list(testout =
(function(x) {
model <- lm(c ~ d, x)
residuals(model)
})(.SD)),
by = a]
## but I want to return a data.frame from the
## anonymous function
tmpdt[ , list(testout =
(function(x) {
model <- lm(c ~ d, x)
tmpresid <- residuals(model)
tmpvalue <- x$b[as.numeric(names(tmpresid))]
data.frame(tmpvalue, tmpresid)
})(.SD)),
by = a]
第二个版本不起作用,因为该函数返回一个data.frame
而不仅仅是一个向量。有没有什么方法可以使这项工作无需在 data.table 之外编写函数调用j
争论?