[R] How to rbind() two matrices that have different column sizes?
Noah Marconi
noah.marconi at noah-marconi.com
Wed Mar 26 16:09:31 CET 2014
Out of curiosity, what's the reason for not using plyr?
If it has to do with installing the package, here's how the rbind.fill
function is implemented in plyr. It may help show you what you'd like to
do:
> plyr::rbind.fill
function (...)
{
dfs <- list(...)
if (length(dfs) == 0)
return()
if (is.list(dfs[[1]]) && !is.data.frame(dfs[[1]])) {
dfs <- dfs[[1]]
}
dfs <- compact(dfs)
if (length(dfs) == 0)
return()
if (length(dfs) == 1)
return(dfs[[1]])
is_df <- vapply(dfs, is.data.frame, logical(1))
if (any(!is_df)) {
stop("All inputs to rbind.fill must be data.frames",
call. = FALSE)
}
rows <- unlist(lapply(dfs, .row_names_info, 2L))
nrows <- sum(rows)
ot <- output_template(dfs, nrows)
setters <- ot$setters
getters <- ot$getters
if (length(setters) == 0) {
return(as.data.frame(matrix(nrow = nrows, ncol = 0)))
}
pos <- matrix(c(cumsum(rows) - rows + 1, rows), ncol = 2)
for (i in seq_along(rows)) {
rng <- seq(pos[i, 1], length = pos[i, 2])
df <- dfs[[i]]
for (var in names(df)) {
setters[[var]](rng, df[[var]])
}
}
quickdf(lapply(getters, function(x) x()))
}
<environment: namespace:plyr>
> plyr::quickdf
function (list)
{
rows <- unique(unlist(lapply(list, NROW)))
stopifnot(length(rows) == 1)
names(list) <- make_names(list, "X")
class(list) <- "data.frame"
attr(list, "row.names") <- c(NA_integer_, -rows)
list
}
<environment: namespace:plyr>
There's a stackoverflow discussion that covers another alternative using
data.tables if that's preferable:
http://stackoverflow.com/questions/18003717/is-there-any-efficient-way-than-rbind-filllist
It looks like dplyr has another alternative implemented in C++ as well:
https://github.com/hadley/dplyr/blob/master/R/rbind.r
On 2014-03-26 10:06, Babak Bastan wrote:
> Hi friends
>
> I would like to rbind two matrices with different column number. How
> can I
> do that? (I dont want to use Plyr package). Is there any way except
> plyr?
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org 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.
More information about the R-help
mailing list