Skip to content
Prev 75142 / 398502 Next

R: cbind

Clark Allan wrote:
Hi, Allan,

How about the following:

cbind.all <- function(..., fill.with = NA) {
   args <- list(...)
   len <- sapply(args, NROW)
   if(diff(rng <- range(len)) > 0) {
     maxlen <- rng[2]
     pad <- function(x, n) c(x, rep(fill.with, n))
     for(j in seq(along = args)) {
       if(maxlen == len[j]) next
       if(is.data.frame(args[[j]])) {
         args[[j]] <- lapply(args[[j]], pad, maxlen - len[j])
         args[[j]] <- as.data.frame(args[[j]])
       } else if(is.matrix(args[[j]])) {
         args[[j]] <- apply(args[[j]], 2, pad, maxlen - len[j])
       } else if(is.vector(args[[j]])) {
         args[[j]] <- pad(args[[j]], maxlen - len[j])
       } else {
         stop("... must only contain data.frames or arrays.")
       }
     }
   }
   do.call("cbind", args)
}

cbind.all(data.frame(a=1),
           data.frame(a=c(2,1)),
           x = 1, y = matrix(1:4,2,2))

cbind.all(a = 1, b = 1:3, d = 1:4)

HTH,

--sundar