Reputation: 441
I would like to compare the frequency of samples from two different observations. The problem is that the first doesn't contain the whole range of numbers of the second. How could I combine these without writing a for loop sorting them based on the x values returned by count? Here's a MWE for clarification:
library(plyr)
a <- c(5, 4, 5, 7, 3, 5, 6, 5, 5, 4, 5, 5, 4, 5, 4, 7, 2, 4, 4, 5, 3, 6, 5, 6, 4, 4, 5, 4, 5, 5, 6, 7, 4)
b <- c(1, 3, 4, 6, 2, 7, 7, 4, 3, 6, 6, 3, 6, 6, 5, 6, 6, 5)
a.count <- count(a)
b.count <- count(b)
My desired result should look somehow like that:
freq.a freq.b
1 1
2 1 1
3 3 2
4 2 10
5 2 13
6 7 4
7 2 3
Upvotes: 0
Views: 605
Reputation: 9687
If you put your data in long format (one row per observation, with a variable for which sample it is from), then you can just make a contingency table:
data.frame(v=df.a, s='a') %>% rbind(data.frame(v=df.b, s='b')) %>%
xtabs(f=~v+s)
Produces:
s
v a b
1 0 1
2 1 1
3 2 3
4 10 2
5 13 2
6 4 7
7 3 2
Upvotes: 2
Reputation: 23101
df <- merge(a.count, b.count, by ='x', all=TRUE)[2:3]
names(df) <- c('freq.a', 'freq.b')
df
freq.a freq.b
1 NA 1
2 1 1
3 2 3
4 10 2
5 13 2
6 4 7
7 3 2
Upvotes: 1