Tas
Tas

Reputation: 1

How can I append multiple columns to a dataframe with column names from a specific vector?

For example, I have a dataframe with 2 columns. I need to append 82 additional columns to this dataframe, with specific column names. These column names are stored in a different vector (dates). How can I do this efficiently? I tried the following:

for(i in 1:length(dates)) {
    peekdata<-cbind(peekdata,dates[i]=0
}

I'm fairly new to R so apologies if its a stupid question

Upvotes: 0

Views: 78

Answers (1)

MrFlick
MrFlick

Reputation: 206546

You can do it without a loop.

First, define some sample data

peekdata  <- data.frame(orig=1:5)
dates <- letters[1:10]

Now do

cbind(peekdata, setNames(replicate(length(dates), 0, simplify=F), dates))

to get

  orig a b c d e f g h i j
1    1 0 0 0 0 0 0 0 0 0 0
2    2 0 0 0 0 0 0 0 0 0 0
3    3 0 0 0 0 0 0 0 0 0 0
4    4 0 0 0 0 0 0 0 0 0 0
5    5 0 0 0 0 0 0 0 0 0 0

But it's odd that you would be doing this. Are you going to fill in values later? Because is usually easier to calculate the values all at once and add them in rather than starting off with a bunch of zeros.

Upvotes: 1

Related Questions