从data.table的`j`内部访问`by`变量 [英] Access `by` variable from within `j` in data.table

查看:74
本文介绍了从data.table的`j`内部访问`by`变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 data.table 并且我正在 j 中进行一些函数调用,我是否可以可以访问 by 变量的当前值吗?

If I have a data.table and I'm doing some function call in the j, do I have access to the current value of the by variable?

library(data.table)
d <- data.table(x=1:10, y=c('a', 'b'))

myfun <- function(DT) {
  print (DT$y)
}


d[, myfun(.SD), by=y]

有关更多上下文,我将第二个参数(另一个 data.table )传递给 myfun ,并希望基于 y 的当前值对其进行子集化。可以用一个虚拟变量来完成,但这似乎令人讨厌...

For more context, I am passing a second argument (another data.table) to myfun and want to subset that based on the current value of y. It could be done with a dummy variable, but that seems yucky...

推荐答案

使用 .BY -这是 by 变量的列表:

Use .BY - which is a list of by variables:

d <- data.table(x=1:10, y=c('a', 'b'))
d[, .BY[[1]], by = y]  # [[1]] to access the first by variable, which is y
                       # if you had by = list(x, y) you'd do .BY[[2]] to access y
#   y V1
#1: a  a
#2: b  b

此外,列表为

d[, .BY$y, by = y]

这篇关于从data.table的`j`内部访问`by`变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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