【发布时间】:2014-11-11 22:30:34
【问题描述】:
我试图让匿名函数在data.table 的j 参数中返回多列。这是一个例子:
## 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 参数之外的函数调用的情况下完成这项工作?
【问题讨论】:
标签: r data.table