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?
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))]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With