[R] combining dataframes with different numbers of columns

hadley wickham h.wickham at gmail.com
Wed Nov 8 04:20:49 CET 2006


> Or, try this:
>
> http://finzi.psych.upenn.edu/R/Rhelp02a/archive/77358.html

It's interesting to compare your implementation:

rbind.all <- function(...) {
   x <- list(...)
   cn <- unique(unlist(lapply(x, colnames)))
   for(i in seq(along = x)) {
     if(any(m <- !cn %in% colnames(x[[i]]))) {
       na <- matrix(NA, nrow(x[[i]]), sum(m))
       dimnames(na) <- list(rownames(x[[i]]), cn[m])
       x[[i]] <- cbind(x[[i]], na)
     }
   }
   do.call(rbind, x)
}

with mine:

rbind.fill <- function (...) {
    dfs <- list(...)
    if (length(dfs) == 0)
        return(list())
    all.names <- unique(unlist(lapply(dfs, names)))
    do.call("rbind", compact(lapply(dfs, function(df) {
        if (length(df) == 0 || nrow(df) == 0)
            return(NULL)
        missing.vars <- setdiff(all.names, names(df))
        if (length(missing.vars) > 0)
            df[, missing.vars] <- NA
        df
    })))
}

they're pretty similar!

Hadley



More information about the R-help mailing list