[R] cbind with vectors of different lengths?

Roman Luštrik romunov at gmail.com
Thu Jun 10 09:41:12 CEST 2010


I wrote a function that cbinds vectors of different lengths. Basically, the
function adds NAs to shorter vectors and cbinds in the end. I'm attaching
the code for guidance.

# This function takes in a list() of vectors and cbinds them into a
data.frame.
timerMelt <- function(x, write.down = FALSE, filename = "output") {
        stopifnot(is.list(x))
       
        filename <- paste(filename, ".txt", sep = "")
        len1 <- length(x[[1]])
        len2 <- length(x[[2]])
        len3 <- length(x[[3]])
        max.len <- max(c(len1, len2, len3))
       
        x.cat1 <- data.frame(rep(NA, max.len))
        x.cat2 <- data.frame(rep(NA, max.len))
        x.cat3 <- data.frame(rep(NA, max.len))
       
        if (len1 < max.len) {
                x.cat1[1:len1,] <- data.frame(x[[1]])
        } else {
                x.cat1 <- data.frame(x[[1]])
        }
       
        if (len2 < max.len) {
                x.cat2[1:len2,] <- data.frame(x[[2]])
        } else {
                x.cat2 <- data.frame(x[[2]])
        }
       
        if (len3 < max.len) {
                x.cat3[1:len3,] <- data.frame(x[[3]])
        } else {
                x.cat3 <- data.frame(x[[3]])
        }
       
        result <- cbind(x.cat1, x.cat2, x.cat3)
        names(result) <- c("s", "p", "r")
       
        if (write.down == TRUE) {
                write.table(result, filename, row.names = FALSE)
        }
       
        return(result)
}

Cheers,
Roman 
-- 
View this message in context: http://r.789695.n4.nabble.com/cbind-with-vectors-of-different-lengths-tp2249680p2250025.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list