[R] adding tables [solution]

Ross Boylan ross at biostat.ucsf.edu
Tue Dec 10 03:34:47 CET 2013


On Mon, 2013-12-09 at 16:09 -0800, Ross Boylan wrote:
> Answering myself...
> On Mon, 2013-12-09 at 15:59 -0800, Ross Boylan wrote:
> > Can anyone recommend a good way to add tables?
> For count data, which were my main concern, it looks as if tabulate with
> nbins will work.  I'm not sure how this works with a cross-classifying
> factor, which I will also need.  It's possible the factor may have
> missing values in some tabulations as well.

By using the levels argument to factor one can ensure that all possible
levels are present.  Then table() will do the right thing.

An example with numbers:
 > t1 <- factor(c(3, 2), levels=1:5)
 > t1
 [1] 3 2
 Levels: 1 2 3 4 5
 > table(t1)
 t1
 1 2 3 4 5
 0 1 1 0 0
This works in arbitrary dimensions.

I figured this out after looking at the code for table, which does the
hard part when there is more than one dimension.

Ross
> 
> For the one dimensional case
>  > t1 <- tabulate(c(1, 2, 2, 4), nbins=5)
>  > t2 <- tabulate(c(2, 3, 5), nbins=5)
>  > t1
>  [1] 1 2 0 1 0
>  > t2
>  [1] 0 1 1 0 1
>  > t1+t2
>  [1] 1 3 1 1 1
> 
> > Ideally I would like
> > t1 <- table(x1)
> > t2 <- table(x2)
> > t1+t2
> > 
> > It t1 and t2 have the same levels this works fine, but I need something
> > that will work even if they differ, e.g.,
> >  > t1
> > 
> >  1 2 4 5
> >  2 1 1 1
> >  > t2 <- table(c(10, 11, 12, 13))
> >  > t1+t2  # apparently does simple vector addition
> > 
> >  1 2 4 5
> >  3 2 2 2
> > whereas I want
> > 1 2 4 5 10 11 12 13
> > 2 1 1 1  1  1  1  1
> > 
> 
>



More information about the R-help mailing list