user2989290
user2989290

Reputation: 47

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?

Upvotes: 0

Views: 126

Answers (3)

user3022612
user3022612

Reputation:

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.

Upvotes: 0

josliber
josliber

Reputation: 44299

You can set variable names using the colnames function. Therefore, your code would look something like:

newdat <- cbind(IA, rand1, rand[2:5])
colnames(newdat) <- c(colnames(IA), paste0("rand", 1:5))

Upvotes: 1

Se&#241;or O
Se&#241;or O

Reputation: 17412

Just do cbind(IA, rand1, rand[2:5]).

Upvotes: 0

Related Questions