Reputation: 79
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
Upvotes: 2
Views: 230
Reputation: 8413
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
Upvotes: 4
Reputation: 69
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.
Upvotes: 0
Reputation: 92282
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
Upvotes: 7
Reputation: 5063
A simple for loop should do the trick:
for (i in 3:16){
u[ , sprintf("a%.0d", i)] <- u[, i-1] + 3
}
Upvotes: 0
Reputation: 388797
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
Upvotes: 1