Home > database >  calculate frequency of unique values per group in R
calculate frequency of unique values per group in R

Time:07-19

How can I count the number of unique values such that I go from:

organisation <- c("A","A","A","A","B","B","B","B","C","C","C","C","D","D","D","D")
variable <- c("0","0","1","2","0","0","1","1","0","0","1","1","0","0","2","2")
df <- data.frame(organisation,variable)

organisation | variable
A            | 0
A            | 1
A            | 2
A            | 2
B            | 0
B            | 0
B            | 1
B            | 1
C            | 0
C            | 0
C            | 1
C            | 1
D            | 0
D            | 2
D            | 2
D            | 2

To:

unique_values | frequency
0,1,2         | 1
0,1           | 2
0,2           | 1

There are only 3 possible sequences:

  • 0,1,2
  • 0,1
  • 0,2

CodePudding user response:

Try this

s <- aggregate(. ~ organisation , data = df , \(x) names(table(x)))
s$variable <- sapply(s$variable , \(x) paste0(x , collapse = ","))
setNames(aggregate(. ~ variable , data = s , length) , c("unique_values" , "frequency"))

  • output
  unique_values frequency
1           0,1         2
2         0,1,2         1
3           0,2         1

CodePudding user response:

You can do something simple like this:

library(dplyr)
library(stringr)

distinct(df) %>% 
  arrange(variable) %>%
  group_by(organisation) %>% 
  summarize(unique_values = str_c(variable,collapse = ",")) %>% 
  count(unique_values)

Output:

  unique_values     n
  <chr>         <int>
1 0,1               2
2 0,1,2             1
3 0,2               1
  • Related