简体   繁体   中英

calculate frequency of unique values per group in R

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM