branch.lizard
branch.lizard

Reputation: 595

Append to each row in a dataframe

It's late and this has to be easy....

Given:

a <- c(1,2)
b <- c(3,4)
foo <- data.frame(a,b)
a.leading <- rep(0, 2)

How do I append a.leading to each row in foo to look like this?

   V1 V2 a b
 1 0  0  1 3
 2 0  0  2 4

I know I could just cbind V1 and V2 with only 0's, but how could one do this with either a loop or vectorized function? V1 and V2 do not have to be the names; I can change them later if needed.

Upvotes: 0

Views: 155

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99321

You shouldn't really loop unless it's either necessary or more efficient. Here you are adding columns to a matrix-like structure, and cbind() is probably the best way to go about it.

You can construct a list for the ... argument in cbind.data.frame(), calling it with do.call().

do.call(cbind.data.frame, c(V = as.list(a.leading), foo))
#   V1 V2 a b
# 1  0  0 1 3
# 2  0  0 2 4

If you don't like that, you can also do

cbind.data.frame(as.list(c(V = a.leading)), foo)
#   V1 V2 a b
# 1  0  0 1 3
# 2  0  0 2 4

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

Here is a method you can use to add columns to a data frame, retaining the same number of rows:

new_cols <- c("V1", "V2")   # new columns "V1" and "V2"
foo[new_cols] <- 0          # assigns 0 to each cell in the new columns

Upvotes: 1

Related Questions