Search code examples
rdata.tablemapply

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?


Solution

  • 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))]