I have searched and can't find the answer to this, though it seems like a pretty basic R question.
I am trying to add multiple columns to a dataframe using a for loop. I would also like each column to be named with the row entry that it corresponds to.
Here is an 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 then tried this:
y <- test$y
for (i in y) { test$i <- rep(c(test$y [i]), times=length(test$y)) }
which gave me this:
> test
x y i
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, what I wanted was 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 am I doing wrong? I'd really appreciate any help you can give!
$is tricky. Trytest[[paste0(i)]] <-