Re: [R] combining dataframes with different numbers of columns

From: hadley wickham <h.wickham_at_gmail.com>
Date: Wed 08 Nov 2006 - 03:20:49 GMT

> 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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Wed Nov 08 18:32:25 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 08 Nov 2006 - 08:30:15 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.