1

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!

1
  • Use of $ is tricky. Try test[[paste0(i)]] <- Commented Apr 9, 2015 at 19:10

1 Answer 1

1

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

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.