[R] appending similar data frames?

Warnes, Gregory R gregory_r_warnes at groton.pfizer.com
Mon Dec 3 23:24:27 CET 2001


 >  From: mmiller3 at iupui.edu [mailto:mmiller3 at iupui.edu]
 >
 >  Dear R gang,
 >  
 >  Can anyone help me sort out how to append one data frame to
 >  another while adding a factor to distinguish which was the
 >  original frame?
 >  

Here is the function that I wrote to accomplish this task.  It will appear
in the next version of the gregmisc library (due sometime January).

concat  <-  function(..., names=NULL)
  {
    tmp  <-  list(...)
    if(is.null(names)) names  <- names(tmp)
    if(is.null(names)) names  <- sapply( as.list(match.call()), deparse)[-1]

    if( any(
            sapply(tmp, is.matrix)
            |
            sapply(tmp, is.data.frame) ) )
      { 
        len  <-  sapply(tmp, function(x) c(dim(x),1)[1] )
        len[is.null(len)]  <-  1
        data <-  rbind( ... )
      }
    else
      {
        len  <- sapply(tmp,length)
        data  <-  unlist(tmp)
        
      }

    namelist  <- factor(rep(names, len), levels=names)
        
    return( data.frame( data, source=namelist) )
  }

You use it like:

> x
  exp size
1   a   10
2   b    9
3   c   10
4   d   12
5   e   11
> y
  exp size
1   a   13
2   b   15
3   c   12
4   d   20
5   e   15
> concat(x,y)
   exp size source
1    a   10      x
2    b    9      x
3    c   10      x
4    d   12      x
5    e   11      x
6    a   13      y
7    b   15      y
8    c   12      y
9    d   20      y
10   e   15      y


LEGAL NOTICE
Unless expressly stated otherwise, this message is confidential and may be privileged. It is intended for the addressee(s) only. Access to this E-mail by anyone else is unauthorized. If you are not an addressee, any disclosure or copying of the contents of this E-mail or any action taken (or not taken) in reliance on it is unauthorized and may be unlawful. If you are not an addressee, please inform the sender immediately.
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list