Albert Perrien
Albert Perrien

Reputation: 1153

Adding a column to a data frame with a variable

I have a data frame that I want to build up programmatically. I have some of the columns in advance, but not all, and I'd like to add them as they come up. So for example:

d <- data.frame("Test" = 0)

gives me this:

  Test
1    0

And the following:

d <- cbind( "Sun" = 0,d)

works as expected:

  Sun Test
1   0    0

But this:

for ( i in daynames) {
    d <- cbind(i = 0 ,d)
}

Yields this:

    i   i   i   i   i   i   i Test
1 Sat Fri Thu Wed Tue Mon Sun    0

Rather than this:

  Sun Mon Tue Wed Thu Fri Sat Test
1   0   0   0   0   0   0   0    0

How can I bind the columns to the data frame with the value of i rather than the identifier itself? Is there some way to do this that is more R-like?

Upvotes: 2

Views: 107

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 146224

Vectorized, I would first bind your new columns together, then bind the data frame to the new columns.

d <- data.frame("Test" = 0)
daynames <- c("Sat", "Fri", "Thu", "Wed", "Tue", "Mon", "Sun") 

dayframe <- do.call(cbind.data.frame, as.vector(rep(0, length(daynames)), mode = "list"))
names(dayframe) <- daynames
cbind(d, dayframe)

Upvotes: 1

user1265067
user1265067

Reputation: 897

I think it could solve

d <- data.frame("Test" = 0)
daynames <- c("Sat", "Fri", "Thu", "Wed", "Tue", "Mon", "Sun") 
for ( i in daynames) {
        d <- cbind( 0 ,d)
    colnames(d)[1] <- i
}

Upvotes: 1

Related Questions