Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table apply function to rows using columns as arguments

I have the following data.table

x = structure(list(f1 = 1:3, f2 = 3:5), .Names = c("f1", "f2"), row.names = c(NA, -3L), class = c("data.table", "data.frame")) 

I would like to apply a function to each row of the data.table. The function func.test uses args f1 and f2 and does something with it and returns a computed value. Assume (as an example)

func.text <- function(arg1,arg2){ return(arg1 + exp(arg2))} 

but my real function is more complex and does loops and all, but returns a computed value. What would be the best way to accomplish this?

like image 890
broccoli Avatar asked Aug 21 '14 16:08

broccoli


2 Answers

The best way is to write a vectorized function, but if you can't, then perhaps this will do:

x[, func.text(f1, f2), by = seq_len(nrow(x))] 
like image 180
eddi Avatar answered Sep 22 '22 03:09

eddi


The most elegant way I've found is with mapply:

x[, value := mapply(func.text, f1, f2)] x #    f1 f2    value # 1:  1  3 21.08554 # 2:  2  4 56.59815 # 3:  3  5 151.4132 

Or with the purrr package:

x[, value := purrr::pmap_dbl(.(f1, f2), func.text)] 
like image 45
mlegge Avatar answered Sep 19 '22 03:09

mlegge