计算 R 数据框列中变量值的唯一组合

count unique combinations of variable values in an R dataframe column

我想计算每个组中出现的变量的唯一组合。 例如:

df <- data.frame(id = c(1,1,1,2,2,2,3,3,4,4,4,5,6,6,7,7,7),
                 status =  c("a","b","c","a","b","c","b","c","b","c","d","b","b","c","b","c", "d"))

> df
   id status
1   1      a
2   1      b
3   1      c
4   2      a
5   2      b
6   2      c
7   3      b
8   3      c
9   4      b
10  4      c
11  4      d
12  5      b
13  6      b
14  6      c
15  7      b
16  7      c
17  7      d

因此,例如,我可以统计给定的“状态”组合出现了多少次。 例如,我看到“a、b、c”总共出现了两次(id 为 1 和 2)。

这些似乎是类似的问题,但我无法弄清楚如何去做,并且在 R 中有更清晰的解释: Count of unique combinations despite order

我想我正在寻找的结果应该是这样的:

abc 2
bc  3
b   1
...

带有 tidyverse 的选项,其中按 'id'、paste 和 'status' 分组并得到 count

library(dplyr)
library(stringr)
df %>% 
   group_by(id) %>% 
   summarise(status = str_c(status, collapse="")) %>% 
   count(status)
# A tibble: 4 x 2
#  status     n
#  <chr>  <int>
#1 abc        2
#2 b          1
#3 bc         2
#4 bcd        2

这是一个基本的 R 选项,来自 aggregate

> aggregate(.~status,rev(aggregate(.~id,df,paste0,collapse = "")),length) 
  status id
1    abc  2
2      b  1
3     bc  2
4    bcd  2

您也可以通过 tapplylapply 使用 apply 系列函数来达到 table

tap <- tapply(df$status, df$id ,FUN= function(x) unique(x)) 
lap <- lapply(tap,FUN = function(x) paste0(x,collapse=""))
status <- unlist(lap)
df1 <- data.frame(table(status))

> df1
  status Freq
1    abc    2
2      b    1
3     bc    2
4    bcd    2