Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data.table column into function when using .SDcols

Tags:

r

data.table

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")]
like image 417
Abiel Avatar asked Jul 14 '26 11:07

Abiel


1 Answers

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.

like image 172
Frank Avatar answered Jul 18 '26 04:07

Frank