I would like to apply one function to multiple columns, using a vector of different values for one parameter.
I have some data:
library(data.table)
df1 <- as.data.table(data.frame(a = c(1,2,3),
b = c(4,5,6)))
cols <- c('a', 'b')
n <- 1:2
And I want to create columns that add n to a and b. Output would look like this:
a b a+1 b+1 a+2 b+2
1: 1 4 2 5 3 6
2: 2 5 3 6 4 7
3: 3 6 4 7 5 8
This post details how to apply one function to multiple columns which I understand how to do.
df1[,paste0(cols,'+1'):= lapply(.SD, function(x) x + 1), .SDcols = cols]
What I don't know is how to apply the same function to multiple columns, substituting n for 1.