Samuel Tan
Samuel Tan

Reputation: 1750

R data.table apply function to sum of two columns

I have a data.table, and I'd like to apply a function over its columns. Usually this is done like so:

dt[, lapply(.SD, func), .SDcols = c("col1", "col2")]

And this would apply the function func over those two columns. What if, however, I'd like to apply it over the sum of those two columns? Something like

dt[, lapply(.SD, func), .SDcols = "col1 + col2"]

obviously doesn't work.

You could generalise this to applying func to the result of another function (in this case, sum) that takes in columns as arguments. I know I can create another column containing the results of the first function, but is there a way around that?

Upvotes: 3

Views: 898

Answers (1)

Frank
Frank

Reputation: 66819

To add the columns, try

dt[, func(Reduce(`+`,.SD)), .SDcols = c("col1","col2")]

This works with more than two columns as well, adding them all together before applying func.

Upvotes: 2

Related Questions