crumbly crumbly - 20 days ago 6
R Question

Add multiple columns simultaneously based on a sequence

I have the following dataframe

u


u <- data.frame(a1 = c("a", "b", "c"), a2 = c(2, 1, 3))


I want to add 14 more columns simultaneously based on a simple sequence which is to create new column by adding constant 3 to the last column.
the resulting data frame:

a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16
a 2 5 8 11 14 17 20 23 26 29 32 35 38 41 44
b 1 4 7 10 13 16 19 22 25 28 31 34 37 40 43
c 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45

Answer

I would vectorize this as follows

u[paste0("a", 3:16)] <- matrix(u$a2 + rep(3*1:14, each = 3), nrow = 3)
u
#   a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16
# 1  a  2  5  8 11 14 17 20 23  26  29  32  35  38  41  44
# 2  b  1  4  7 10 13 16 19 22  25  28  31  34  37  40  43
# 3  c  3  6  9 12 15 18 21 24  27  30  33  36  39  42  45