2
votes

Here is my code:

df1 <- data.frame(Intercept = .4, x1=.4, x2=.2, x3=.7)
df2 <- data.frame(Interceptlego = .5,x2=.8)
df3 <- data.frame()
myList <- list(df1, df2, df3)
do.call(rbind.fill, myList)

I wonder how can I rbind df3 into a single data frame as "NA"s?

I found an article from r_blogger about Combining vectors or data frames of unequal length into one data frame. http://www.r-bloggers.com/r-combining-vectors-or-data-frames-of-unequal-length-into-one-data-frame/

But the data frame I got from my data, some of them are empty which contains "<0 rows> (or 0-length row.names)"

What I want to accomplish is like this

  Intercept  x1  x2  x3 Interceptlego
1       0.4 0.4 0.2 0.7            NA
2        NA  NA 0.8  NA           0.5
3        NA  NA NA   NA            NA
1
Well, put NA values in the empty data.frame to make sure that it contains what you expect? An empty data.frame is empty. Combining it with another data.frame shouldn't change the other data.frame. - Roland
Thank you for replying. Please see my update on what I want to accomplish. - Luzhi Deng

1 Answers

2
votes

I don't really follow your logic. An empty data.frame doesn't contain any observations and should not result in a row after rbinding.

Anyway, assuming you know a column name that occurs at least once:

myList <- lapply(myList, function(df) {
  if (!ncol(df)) df <- data.frame(Intercept = NA)
  df
})
library(data.table)
rbindlist(myList, fill = TRUE)
#   Intercept  x1  x2  x3 Interceptlego
#1:       0.4 0.4 0.2 0.7            NA
#2:        NA  NA 0.8  NA           0.5
#3:        NA  NA  NA  NA            NA

Use setDF subsequently if you prefer not having a data.table.