Add multiple columns using for loop in R and name with row entry -
i have searched , can't find answer this, though seems pretty basic r question.
i trying add multiple columns dataframe using loop. each column named row entry corresponds to.
here example:
> test <- data.frame(cbind(x=1, y=1:10)) > test x y 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10
i tried this:
y <- test$y (i in y) { test$i <- rep(c(test$y [i]), times=length(test$y)) }
which gave me this:
> test x y 1 1 10 1 2 10 1 3 10 1 4 10 1 5 10 1 6 10 1 7 10 1 8 10 1 9 10 1 10 10
however, wanted this:
> test x y 1 2 3 4 5 6 7 8 9 10 1 1 1 2 3 4 5 6 7 8 9 10 1 2 1 2 3 4 5 6 7 8 9 10 1 3 1 2 3 4 5 6 7 8 9 10 1 4 1 2 3 4 5 6 7 8 9 10 1 5 1 2 3 4 5 6 7 8 9 10 1 6 1 2 3 4 5 6 7 8 9 10 1 7 1 2 3 4 5 6 7 8 9 10 1 8 1 2 3 4 5 6 7 8 9 10 1 9 1 2 3 4 5 6 7 8 9 10 1 10 1 2 3 4 5 6 7 8 9 10
what doing wrong? i'd appreciate can give!
try
v1 <- seq_len(nrow(test)) #or #v1 <- test$y cbind(test,setnames(data.frame(as.list(v1)), v1)) # x y 1 2 3 4 5 6 7 8 9 10 #1 1 1 1 2 3 4 5 6 7 8 9 10 #2 1 2 1 2 3 4 5 6 7 8 9 10 #3 1 3 1 2 3 4 5 6 7 8 9 10 #4 1 4 1 2 3 4 5 6 7 8 9 10 #5 1 5 1 2 3 4 5 6 7 8 9 10 #6 1 6 1 2 3 4 5 6 7 8 9 10 #7 1 7 1 2 3 4 5 6 7 8 9 10 #8 1 8 1 2 3 4 5 6 7 8 9 10 #9 1 9 1 2 3 4 5 6 7 8 9 10 #10 1 10 1 2 3 4 5 6 7 8 9 10
or
test[paste(v1)] <- as.list(v1)