1

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.

Slash
  • 501
  • 2
  • 9

2 Answers2

1

Here is a base R solution

df1out <- cbind(df1,do.call(cbind,lapply(c(1,2), function(k) setNames(df1+k,paste0(names(df1),"+",k)))))

such that

> df1out
   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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

We can also use outer

cbind(df1, df1[,  lapply(.SD, function(x) outer(x, n, `+`))])

Or another option is

nm1 <- paste0(cols, "+", rep(n, each = length(cols)))
df1[, (nm1) := lapply(n, `+`, .SD)]
akrun
  • 874,273
  • 37
  • 540
  • 662