1

如何合并(添加)列联表:

> (t1 <- table(c("a","b","b","c")))

a b c 
1 2 1 
> (t2 <- table(c("c","d","d","a")))

a c d 
1 1 2 

我要这个:

a b c d
2 2 2 2
4

3 回答 3

4

您可以使用splitsapply

> T <- c(t1, t2)
>  sapply(split(T, names(T)), sum)
a b c d 
2 2 2 2 

或直接使用tapply@Arun指出的

> tapply(T, names(T), sum)
a b c d 
2 2 2 2 
于 2013-06-10T18:55:27.050 回答
0

这是我能想到的:

> (t1 <- table(c("a","b","b","c")))

a b c 
1 2 1 
> (t2 <- table(c("c","d","d","a")))

a c d 
1 1 2 
> (n <- sort(union(names(t1),names(t2))))
[1] "a" "b" "c" "d"
> (t1 <- t1[n])

   a    b    c <NA> 
   1    2    1   NA 
> names(t1) <- n
> t1
 a  b  c  d 
 1  2  1 NA 
> t1[is.na(t1)] <- 0
> t1
a b c d 
1 2 1 0 
> t2 <- t2[n]
> names(t2) <- n
> t2
 a  b  c  d 
 1 NA  1  2 
> t2[is.na(t2)] <- 0
> t2
a b c d 
1 0 1 2 
> t1+t2
a b c d 
2 2 2 2 

我认为必须有更好的方法...

于 2013-06-10T18:50:51.643 回答
0

这有效:

library(plyr)

colSums(rbind.fill(data.frame(t(unclass(t1))), data.frame(t(unclass(t2)))),
        na.rm = T)
于 2013-06-10T18:53:46.740 回答