Home > Net >  Squaring colums with lapply
Squaring colums with lapply

Time:11-10

I hope this question is simple enough to not warrant a reproducible example.

I have the following syntax:

library(data.table)
setDT(table_selection)[, (vars_of_interest) := lapply(.SD, sqrt, na.rm=TRUE), by = year, .SDcols=sds_of_interest]

I would like to square a sequence of columns instead of taking the square root, but I cannot find a similar function.

How should I do this?

CodePudding user response:

This should work.

setDT(table_selection)[, (vars_of_interest) := lapply(.SD, function(x) x^2), by = year, .SDcols=sds_of_interest]

CodePudding user response:

A very pure way:

setDT(table_selection)[, (vars_of_interest) := lapply(.SD, `^`, 2),
                       by = year,
                       .SDcols = sds_of_interest]
  • Related