[R] Combining columns of different length

Rolf Turner rolf at math.unb.ca
Tue Oct 26 14:35:11 CEST 2004


In R all things are possible:

rcb <- function (...) {
# rcb <--> ``ragged cbind''
xxx <- list(...)
n <- max(unlist(lapply(xxx,function(x){ifelse(is.matrix(x),nrow(x),
                                              length(x))})))
yyy <- lapply(xxx,function(x,n){if(is.matrix(x))
                        rbind(x,matrix(NA,ncol=ncol(x),nrow=n))
                        else c(x,rep(NA,n-length(x)))},n=n)
do.call("cbind",yyy)
}


				cheers,

					Rolf Turner
					rolf at math.unb.ca

Federico Gherardini wrote:

> Simple and direct question....  Is it possible to add a shorter
> column to a data frame or matrix in such a way that the missing
> values are replaced with NAs?  For example suppose I have
> 
> 3   2
> 4   2
> 5   8
> 
> and I want to add a column
> 
> 3
> 3
> 
> to get...
> 
> 3   2   3
> 4   2   3
> 5   8   NA
> 
> Thanks
> 
> Federico




More information about the R-help mailing list