Search code examples
r

using a for loop to add columns to a data frame


I am new to R and it seems like this shouldn't be a difficult task but I cannot seem to find the answer I am looking for. I am trying to add multiple vectors to a data frame using a for loop. This is what I have so far and it works as far as adding the correct columns but the variable names are not right. I was able to fix them by using rename.vars but was wondering if there was a way without doing that.

for (i in 1:5) {
    if (i==1) {
    alldata<-data.frame(IA, rand1) }
    else {
    alldata<-data.frame(alldata, rand[[i]]) }
}

Instead of the variable names being rand2, rand3, rand4, rand5, they show up as rand..i.., rand..i...1, rand..i...2, and rand..i...3.

Any Suggestions?


Solution

  • If you're creating your variables in a loop, you can assign the names during the loop

    alldata <- data.frame(IA)
    for (i in 1:5) {alldata[paste0('rand', i)] <- rand[[i]]}
    

    However, R is really slow at loops, so if you are trying to do this with tens of thousands of columns, the cbind and rename approach will be much faster.