gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:51:34 24 4
gpt4 key购买 nike

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/

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