r - 我可以在同一个 `j` 参数中使用在 `j` 中新创建的变量吗?

标签 r data.table

j参数在 data.table , 是否有语法允许我在相同的 j 中引用以前创建的变量陈述?我在想类似 Lisp 的东西 let*构造。

library(data.table)
set.seed(22)
DT <- data.table(a = rep(1:5, each = 10),
                 b = sample(c(0,1), 50, rep = TRUE))

DT[ ,
   list(attempts = .N,
        successes = sum(b),
        rate = successes / attempts),
   by = a]

这导致
# Error in `[.data.table`(DT, , list(attempts = .N, successes = sum(b),  : 
#  object 'successes' not found

我明白为什么,但在同一个 j 中是否有不同的方法来实现这一点?

最佳答案

这将解决问题:

DT[ , {
    list(attempts = attempts <- .N,
         successes = successes <- sum(b),
         rate = successes/attempts)
    },  by = a]
#    a attempts successes rate
# 1: 1       10         5  0.5
# 2: 2       10         6  0.6
# 3: 3       10         3  0.3
# 4: 4       10         5  0.5
# 5: 5       10         5  0.5

FWIW,this closely related data.table feature request将使 +/- 在您的问题中使用的语法成为可能。从链接页面引用:

Summary:

Iterative RHS of := (and `:=`(...)), and multiple := inside j = {...} syntax

Detailed description

e.g. DT[, `:=`( m1 = mean(a), m2 = sd(a), s = m1/m2 ), by = group]

where s can use previous lhs names ( using the word 'iterative' tries to convey that ).

关于r - 我可以在同一个 `j` 参数中使用在 `j` 中新创建的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592708/

相关文章:

r - 在 r 中混淆聚类数据并保护隐私的技术

r - 将某一特定列求和为每 2 种和 3 种可能组合中的 n 列

r data.table 更新join中的多列

r - 在 R 中绘制包含逗号的文本或标签子脚本

r - 在 data.table 的列中“分组”实数

r - 使用 data.table 同时排序、行过滤和列选择

r - data.table 中的区间类

python - 如何在Shiny中通过R运行Python文件中的特定函数?

r - 在 R 中将数字打印为减少的分数

r - 如何在R中直接绘制h2o模型对象的ROC