[R] rbind with missing columns

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Fri Apr 30 15:33:35 CEST 2004


here is another solution:

A <- data.frame(a = c(1,2,3), b = c(4,5,6))
B <- data.frame(a = c(1,2,3))
C <- data.frame(b=4:6)

rbind.data.frame.NA<-function(...){
  N<-unique(unlist(lapply(list(...),names)))
  result<-NULL
  for(DF in list(...)){
    x<-as.data.frame(lapply(N,function(x)if(x %in% names(DF)) DF[,x] 
else NA))
    names(x)<-N
    result<-rbind(result,x)
  }
  result
}

rbind.data.frame.NA(B,A,C)

@
output-start
Fri Apr 30 15:21:21 2004
    a  b
1   1 NA
2   2 NA
3   3 NA
11  1  4
21  2  5
31  3  6
12 NA  4
22 NA  5
32 NA  6
output-end

Peter Wolf

Duncan Murdoch wrote:

>On Fri, 30 Apr 2004 13:47:35 +0200, <klaus.thul at infineon.com> wrote :
>
>  
>
>>Hello,
>>
>>I have several data sets, which I want to combine column-by-column using
>>"rbind" (the data sets have ~100 columns). The problem is, that in some
>>data sets some of the columns are missing.
>>
>>Simply using rbind gives me:
>>"Error in match.names(clabs, names(xi)) : names don't match previous
>>names"
>>
>>Is there a simple way to make R do the rbind despite the missing columns
>>and to fill out the missing data with NA's? (I could program this
>>somehow, but probably there is one very simple solution available)
>>    
>>
>
>It's not there already as far as I know, but it's not too hard to
>write a new rbind that does this:
>
>newrbind <- function(A,B) {
>  anames <- names(A)
>  bnames <- names(B)
>  notinb <- anames[!(anames %in% bnames)]
>  if (length(notinb)) B[[notinb]] <- rep(NA, nrow(B))
>  notina <- bnames[!(bnames %in% anames)]
>  if (length(notina)) A[[notina]] <- rep(NA, nrow(A))
>  rbind(A, B)
>}
>
>This only works on data.frames; if you want it to work as generally as
>the real rbind, you'll need to add some extra conversions at the
>start.
>
>Duncan Murdoch
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>  
>




More information about the R-help mailing list