2

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?

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Is there any way to do this in a vectorized form?
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.