gpt4 book ai didi

r - data.table:j 中的匿名函数

转载 作者:行者123 更新时间:2023-12-04 01:59:16 24 4
gpt4 key购买 nike

我试图让匿名函数返回 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 之外的函数调用的情况下完成这项工作争论?

最佳答案

你不需要匿名函数 - 你可以在 { } 中包含任何你想要的表达式(匿名机构)在 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 :
  • 评论在 示例 ?data.table :

  • anonymous lambda in j: j accepts any valid expression. TO REMEMBER: every element of the list becomes a column in result.


  • data.table FAQ 2.8 What are the scoping rules for j expressions?

  • No anonymous function is passed to j. Instead, an anonymous body [{ }] is passed to j [...] Some programming languages call this a lambda.


  • Andrew Brooks 关于 { } 使用的博客文章在 j :Suppressing intermediate output with {}
  • 关于r - data.table:j 中的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898162/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com