Unused argument

Viewed 297

I am trying to understand how .SDcols and .SD work. I got the following function which I can apply directly in datatable, but not via lapply. I am wondering if there is an equivalent with .SD which allows to pass multiple parameters to the function body. The below code always gives "Unused argument..."

DT <- data.table(a=1:10,b=2:11,c=3:12,ID=c(rep("A",5),rep("B",5)))
doSomething <- function(a,b,c){
tmp <- a/b
tmp2 <- sqrt(tmp)^2000000
tmp3 <- tmp2 + tmp
return(rep(tmp3,length(a)))
}
DT[,doSomething(a,b,c)] # works
DT[,lapply(.SD,doSomething,a,b,c),.SDcol=c("a","b","c")]
DT[,lapply(.SD,doSomething,a=a,b=b,c=c),.SDcol=c("a","b","c")]
1 Answers

If we need to use .SD

out2 <- DT[, do.call(doSomething, .SD), .SDcols = a:c]

which can be otherwise written as

DT[, doSomething(.SD[[1]], .SD[[2]], .SD[[3]]), .SDcols = a:c]

-checking

out1 <- DT[,doSomething(a,b,c)] 
identical(out1, out2)
#[1] TRUE

Related