Reputation: 25
Say I initialize an empty data frame like so:
df = data.frame(matrix(ncol = 5, nrow = 0))
colnames(df) <- c("c1","c2","c3","c4","c5")
And wish to populate the data frame rows with vectors such as
v1 =
c2 c3 c4
6 4 3
v2 =
c1 c3 c5
2 5 7
So that df
will look like
c1 c2 c3 c4 c5
0 6 4 3 0
2 0 5 0 7
What's the most efficient way to go about this? The vectors are originally lists, which I was converting to a matrix and attempting to append df
with so that the column labels are maintained throughout. However, I'm struggling to find an automated way to fill the missing element values since the columns themselves don't exist (ie v1 has no "c1" column).
Upvotes: 0
Views: 32
Reputation: 1810
Assuming your vectors are still named lists, like
v1 <- as.list(setNames(c(6,4,3),c("c2","c3","c4")))
v2 <- as.list(setNames(c(6,4,3),c("c1","c3","c5")))
(so you don't have to do the step of processing them to vectors), you can use
df = data.frame(matrix(ncol = 5, nrow = 0))
colnames(df) <- c("c1","c2","c3","c4","c5")
listOfNamedValueLists <- list(v1,v2)
df <- do.call(plyr::rbind.fill,c(list(df),lapply(listOfNamedValueLists,data.frame)))
df[is.na(df)] <- 0
Note that appending df
to the list as first element ensures you that the names are in right order.
Upvotes: 0
Reputation: 545608
The following works:
df[1L, c('c2', 'c3', 'c4')] = v1
df[2L, c('c1', 'c3', 'c5')] = v2
df[is.na(df)] = 0
If your vectors are named, it’s even easier:
df[1L, names(v1)] = v1
df[2L, names(v2)] = v2
df[is.na(df)] = 0
Upvotes: 0