data.table:j中的匿名函数 [英] data.table: anonymous function in j
问题描述
我试图让一个匿名函数在 data.table
的 j
参数中返回多个列。这是一个示例:
I'm trying to have an anonymous function return multiple columns in the j
argument of a data.table
. Here's an example:
## 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]
Th第二个版本不起作用,因为该函数返回 data.frame
而不是向量。是否有任何方法可以在不编写data.table j
参数之外编写函数调用的情况下完成这项工作?
The second version doesn't work because the function returns a data.frame
instead of just a vector. Is there any way to make this work without writing the function call outside of the data.table j
argument?
推荐答案
您不需要匿名函数-您可以将要包装在 {}
(匿名 body )in j
:
You don't need anonymous functions - you can have whatever expression you want wrapped in { }
(anonymous body) in j
:
tmpdt[, {
model <- lm(c ~ d, .SD)
tmpresid <- residuals(model)
tmpvalue <- b[as.numeric(names(tmpresid))]
list(tmpvalue, tmpresid) # every element of the list becomes a column in result
}
, by = a]
在 {}
的一些文档> j :
Some documentation on the use of anonymous body { }
in j
:
- 在
中的示例中添加注释? data.table
:
- Comment in Examples in
?data.table
:
中的匿名lambda j
:j
接受任何有效的表达式。要记住:列表
的每个元素都会成为结果列。
anonymous lambda in
j
:j
accepts any valid expression. TO REMEMBER: every element of thelist
becomes a column in result.
data.table
FAQ 2.8 What are the scoping rules forj
expressions?
没有匿名函数传递给
j
。而是将匿名 body [{}
]传递给j
[... ]某些编程语言将其称为 lambda 。
No anonymous function is passed to
j
. Instead, an anonymous body [{ }
] is passed toj
[...] Some programming languages call this a lambda.
- 安德鲁·布鲁克斯(Andrew Brooks)关于在
j
中使用{}
的博客文章:使用{} $ b $抑制中间输出b
- Blog post by Andrew Brooks on the use of
{ }
inj
: Suppressing intermediate output with {}
这篇关于data.table:j中的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!