使用.SDcols时,将data.table列传递给函数 [英] Pass data.table column into function when using .SDcols

查看:111
本文介绍了使用.SDcols时,将data.table列传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 DT [,lapply(.SD,func),by = group,.SDcols = cols] > data.table ,但我想将 DT 的列传递给 func()。有办法让这个工作吗?例如,

I would like to use the DT[, lapply(.SD, func), by=group, .SDcols=cols] syntax in a data.table, but I would like to pass a column of DT to func(). Is there a way to get this to work? For example,

indexfunc <- function(col, indexcol, indexvalue)
  col/col[indexcol==indexvalue]

DT <- data.table(group=c('A','A','B','B'), indexkey=c(1,2,1,2), value=1:4)

# Works
DT[, indexfunc(value, indexkey, 2), by=group]

# Fails, Error in indexfunc(value, indexkey, 2) : object 'indexkey' not found
DT[, lapply(.SD, indexfunc, indexkey, 2), by=group, .SDcols=c("value")]


推荐答案

我认为这里的策略必然涉及坏的编程, / p>

I think the strategy here necessarily entails bad programming, but

DT[,lapply(
  .SD[,"value",with=FALSE], 
  indexfunc,indexcol= indexkey,indexvalue= 2
), by=group]

   group value
1:     A  0.50
2:     A  1.00
3:     B  0.75
4:     B  1.00

OP中的方法无效,因为 .SDcols 限制 j 中 DT [i,j] 。我认为 lapply 中使用的函数的参数也必须命名。

The approach in the OP didn't work because .SDcols restricts the set of columns available in j of DT[i,j]. I think the arguments to the function used in lapply must also be named.

这篇关于使用.SDcols时,将data.table列传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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