user2426619
user2426619

Reputation: 33

Trying to add multiple sequentially number columns to data frame in r

I need to add 7 empty columns (to represent days of the week) to an existing data frame and especially helpfull if they can be preceeded by the word "Day"

I have previously used 7 lines like this

DF$'Day 1' <- ''

DF$'Day 2' <- ''

Is it possible to shorten this, possibly using a loop?

eg. for(i in 1:7) {DF@'Day [i]' <- ''}

Which obviously doesn't work otherwise I wouldn't need to be asking.

Upvotes: 3

Views: 2684

Answers (2)

Ben Kujala
Ben Kujala

Reputation: 1

If you need to create an empty data frame then you can do the following:

DF <- as.data.frame(matrix(nrow=0, ncol=20))
names(DF) <- paste("Val", 1:20, sep="")

Upvotes: 0

John
John

Reputation: 23758

If you attempt to assign to non-existent columns then they just get created for you automagically.

DF <- data.frame(x = 1:4, y = 'hi')
days <- paste0('Day',1:7)
DF[,days] <- NA

Upvotes: 3

Related Questions