[R] merge counts from table()

PIKAL Petr petr.pikal at precheza.cz
Tue Aug 14 11:39:59 CEST 2012


Hi

If your x and y are factors it seems to be easy, just add all levels in both.

x.f<-factor(x, levels=1:5)
y.f<-factor(y, levels=1:5)

table(x.f)+table(y.f)
x.f
1 2 3 4 5 
1 2 2 2 1 

If you just have output from table(x) without possibility to add levels you can go with merge


> mm <- merge(as.data.frame(table(x)), as.data.frame(table(y)), by.x="x", by.y="y",all=T)
  x Freq.x Freq.y
1 1      1     NA
2 2      1      1
3 3      1      1
4 4      1      1
5 5     NA      1

Here you need to change NA to 0 and perform rowSums.

mm[is.na(mm)]<-0
rowSums(mm[-1])
[1] 1 2 2 2 1
t(cbind(mm[,1],rowSums(mm[-1])))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    2    2    1

Regards
Petr

> Hi everyone,
> 
> Is there an easy way to combine the counts from table()?
> 
> Let's say that I have:
> x<-1:4
> y<-2:5
> 
> I want to replicate:
> table(c(x,y))
> 
> using only table(x) and table(y) as input.
> 
> The reason is that it's cumbersome to carry all the values around when
> all I care about are the counts. The actual situation has about a
> billion counts over ~150 categories.
> 
> I know there's got to be a number of ways of doing things (plyr comes
> to mind), but I can't seem to find how to accomplish it.
> 
> Thanks,
> 
> François Pepin
> ______________________________________________
> 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