[datatable-help] How can I apply a function of 2 columns to multiple other columns with a by clause

Arunkumar Srinivasan aragorn168b at gmail.com
Wed Oct 14 13:45:18 CEST 2015


Will become more natural when https://github.com/Rdatatable/data.table/issues/495 is fixed. I’ll work on this at some point for v1.9.8. I don’t have a time frame yet.

First, for both cases, I’d suggest using `Map()`. Second, as a temporary solution, I’d suggest using `mget()`.

#when there is no by it is easy 
DT[, (rCols) := Map(f, mget(xCols), list(x4))] 

#when there is a by it fails (offcourse DT$x4 is too big) 
DT[, (rCols) := Map(f, mget(xCols), list(x4)), by=y] 

When #495 is fixed, `mget(xCols)` can be replaced with `.SD` along with `.SDcols = xCols`.

-- 
Arun

On 14 October 2015 at 13:33:37, statquant3 (statquant at outlook.com) wrote:

Hello, I am looking to  
* update several columns by  
* applying a function f (to each of those columns) that would use those  
columns AND another one.  

If there is no "by" I make it work  
How can I do the same with a "by" :  

Bellow an example (as I can't be very clear)  

#data setup  
library(data.table)  
set.seed(1)  
N <- 101  
DT <-  
data.table(x1=rnorm(N),x2=rnorm(N),x3=rnorm(N),x4=rnorm(N),y=letters[sample(5,size=N,replace=T)])  

#function to be applied  
f <- function(x,y){return( frank(x/y,na.last='keep') )}  
#column names  
xCols <- paste0('x',1:3)  
rCols <- paste0('r',1:3)  

#when there is no by it is easy  
DT[,(rCols):=lapply(FUN=f,X=.SD,y=DT$x4),.SDcols=xCols]  

#when there is a by it fails (offcourse DT$x4 is too big)  
DT[,(rCols):=lapply(FUN=f,X=.SD,y=DT$x4),.SDcols=xCols,by=.(y)]  




--  
View this message in context: http://r.789695.n4.nabble.com/How-can-I-apply-a-function-of-2-columns-to-multiple-other-columns-with-a-by-clause-tp4713576.html  
Sent from the datatable-help mailing list archive at Nabble.com.  
_______________________________________________  
datatable-help mailing list  
datatable-help at lists.r-forge.r-project.org  
https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20151014/b65106e2/attachment.html>


More information about the datatable-help mailing list