Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Last active April 12, 2020 22:51
Show Gist options
  • Save mrdwab/6789277 to your computer and use it in GitHub Desktop.
Save mrdwab/6789277 to your computer and use it in GitHub Desktop.
Cbind for unequal length vectors.
padNA <- function (mydata, rowsneeded, first = TRUE)
{
temp1 = colnames(mydata)
rowsneeded = rowsneeded - nrow(mydata)
temp2 = setNames(
data.frame(matrix(rep(NA, length(temp1) * rowsneeded),
ncol = length(temp1))), temp1)
if (isTRUE(first)) rbind(mydata, temp2)
else rbind(temp2, mydata)
}
dotnames <- function(...) {
vnames <- as.list(substitute(list(...)))[-1L]
vnames <- unlist(lapply(vnames,deparse), FALSE, FALSE)
vnames
}
Cbind <- function(..., first = TRUE) {
Names <- dotnames(...)
datalist <- setNames(list(...), Names)
nrows <- max(sapply(datalist, function(x)
ifelse(is.null(dim(x)), length(x), nrow(x))))
datalist <- lapply(seq_along(datalist), function(x) {
z <- datalist[[x]]
if (is.null(dim(z))) {
z <- setNames(data.frame(z), Names[x])
} else {
if (is.null(colnames(z))) {
colnames(z) <- paste(Names[x], sequence(ncol(z)), sep = "_")
} else {
colnames(z) <- paste(Names[x], colnames(z), sep = "_")
}
}
padNA(z, rowsneeded = nrows, first = first)
})
do.call(cbind, datalist)
}
@mrdwab
Copy link
Author

mrdwab commented Oct 2, 2013

Here's a small example:

A <- 1:10
B <- 3:5
C <- matrix(1:12, nrow = 3)
D <- data.frame(A = 1:2, B = c("a", "b"))

Cbind(A, B, C, D)
#     A  B C_1 C_2 C_3 C_4 D_A  D_B
#1   1  3   1   4   7  10   1    a
#2   2  4   2   5   8  11   2    b
#3   3  5   3   6   9  12  NA <NA>
#4   4 NA  NA  NA  NA  NA  NA <NA>
#5   5 NA  NA  NA  NA  NA  NA <NA>
#6   6 NA  NA  NA  NA  NA  NA <NA>
#7   7 NA  NA  NA  NA  NA  NA <NA>
#8   8 NA  NA  NA  NA  NA  NA <NA>
#9   9 NA  NA  NA  NA  NA  NA <NA>
#10 10 NA  NA  NA  NA  NA  NA <NA>

Cbind(A, B, C, D, first = FALSE)
#     A  B C_1 C_2 C_3 C_4 D_A  D_B
#1   1 NA  NA  NA  NA  NA  NA <NA>
#2   2 NA  NA  NA  NA  NA  NA <NA>
#3   3 NA  NA  NA  NA  NA  NA <NA>
#4   4 NA  NA  NA  NA  NA  NA <NA>
#5   5 NA  NA  NA  NA  NA  NA <NA>
#6   6 NA  NA  NA  NA  NA  NA <NA>
#7   7 NA  NA  NA  NA  NA  NA <NA>
#8   8  3   1   4   7  10  NA <NA>
#9   9  4   2   5   8  11   1    a
#10 10  5   3   6   9  12   2    b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment