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")]
I think the strategy here necessarily entails bad programming, but
DT[,lapply(
.SD[,"value"],
indexfunc,indexcol= indexkey,indexvalue= 2
), by=group]
gives the output
group value
1: A 0.50
2: A 1.00
3: B 0.75
4: B 1.00
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With