在 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:=
insidej = {...}
syntaxDetailed 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/