2

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
0

5 Answers 5

7

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
Sign up to request clarification or add additional context in comments.

Comments

4
u[paste0("a",3:16)] = as.data.frame(lapply(1:14, function(x) u$a2+3*x))
#  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

Comments

1

We can use sapply to loop over every element of a2 column and generate a sequence from that number , increment it by 3 and output 15 values (column 2 is over written here)

temp = cbind(u[1], t(sapply(u$a2, function(x) seq(x, by = 3, length.out = 15))))
temp

#  a1 1 2 3  4  5  6  7  8  9 10 11 12 13 14 15
#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

Comments

0

A simple for loop should do the trick:

for (i in 3:16){
  u[ , sprintf("a%.0d", i)] <- u[, i-1] + 3
}

Comments

0
  u<-data.frame(a1=c("a","b","c"),a2=c(2,1,3))
 for(i in 1:14){ 
 u[,ncol(u)+1] <-  u[,ncol( u)]+3
   names(u)[ncol(u)]<-paste0("a",ncol(u))
 }

This uses a for loop and gives you the column names you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.