sesselastronaut sesselastronaut - 10 days ago 6
R Question

Compare frequencies of samples in r

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

Answer
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
Comments