How to sum counts across tables that may contain partially different categories in R?
问题 How do I merge (add) contingency tables: > (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 I want this: a b c d 2 2 2 2 回答1: You can do it using split and sapply > T <- c(t1, t2) > sapply(split(T, names(T)), sum) a b c d 2 2 2 2 Or directly using tapply as pointed out by @Arun > tapply(T, names(T), sum) a b c d 2 2 2 2 回答2: Here is what I was able to come up with: > (t1 <- table(c("a","b","b","c"))) a b c 1 2 1 > (t2 <- table(c("c","d","d","a")))