data.table:j中的匿名函数 [英] data.table: anonymous function in j

查看:95
本文介绍了data.table: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:


  1. 中的示例中添加注释? data.table

  1. Comment in Examples in ?data.table:




中的匿名lambda j j 接受任何有效的表达式。要记住:列表的每个元素都会成为结果列。

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




  1. data.table 常见问题解答2.8 j 表达式?

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




没有匿名函数传递给 j 。而是将匿名 body [ {} ]传递给 j [... ]某些编程语言将其称为 lambda

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




  1. 安德鲁·布鲁克斯(Andrew Brooks)关于在 j 中使用 {} 的博客文章:使用{}
  2. $ b $抑制中间输出b
  1. Blog post by Andrew Brooks on the use of { } in j: Suppressing intermediate output with {}

这篇关于data.table:j中的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆