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

时间:2020-07-23 20:11:57

标签: r rle

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

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中有更清晰的解释: Counting unique combinations Count of unique combinations despite order

我认为我正在寻找的结果将是这样的:

abc 2
bc  3
b   1
...

3 个答案:

答案 0 :(得分:5)

带有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

答案 1 :(得分:2)

这是通过aggregate

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

答案 2 :(得分:1)

您也可以将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