简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM