我有一个数据框,其中显示了三种颜色类别的成员资格。 数字代表唯一的ID。一个ID可以是一个组或多个组的一部分。

dat <- data.frame(BLUE = c(1, 2, 3, 4, 6, NA),
                  RED = c(2, 3, 6, 7, 9, 13),
                  GREEN = c(4, 6, 8, 9, 10, 11))

或供视觉参考:
BLUE  RED  GREEN
1     2    4
2     3    6
3     6    8
4     7    9
6     9    10
NA    13   11

我需要确定并统计个人和跨组成员身份(即,只有红色的ID数量,红色和蓝色的ID数量等等)。我想要的输出如下。请注意,IDs列仅供参考,该列不会出现在预期的输出中。
COLOR                TOTAL  IDs (reference only, not needed in final output)
RED                  2      (7, 13)
BLUE                 1      (1)
GREEN                3      (8, 10, 11)
RED, BLUE            3      (2, 3, 6)
RED, GREEN           2      (6, 9)
BLUE, GREEN          2      (4, 6)
RED, BLUE, GREEN     1      (6)

有谁知道在R中执行此操作的有效方法吗?谢谢!

最佳答案

library(dplyr)
library(tidyr)

cbind(dat, row = 1:6) %>%
  gather(COLOR, IDs, -row) %>%
  group_by(IDs) %>%
  nest(COLOR, .key="COLOR") %>%
  mutate(COLOR = sapply(COLOR, as.character)) %>%
  drop_na %>%
  group_by(COLOR) %>%
  add_count(name="TOTAL") %>%
  group_by(COLOR, TOTAL) %>%
  nest(IDs, .key = "IDs") %>%
  as.data.frame

#>                       COLOR TOTAL       IDs
#> 1                      BLUE     1         1
#> 2          c("BLUE", "RED")     2      2, 3
#> 3        c("BLUE", "GREEN")     1         4
#> 4 c("BLUE", "RED", "GREEN")     1         6
#> 5                       RED     2     7, 13
#> 6         c("RED", "GREEN")     1         9
#> 7                     GREEN     3 8, 10, 11



NA包中还有一种更传统的方法来处理venn:

library(purrr)
library(magrittr)
library(venn)

as.list(dat) %>%
  map(discard, is.na) %>%
  compact() %>%
  venn() %>%
  print

    #>                BLUE RED GREEN counts
    #>                   0   0     0      0
    #> GREEN             0   0     1      3
    #> RED               0   1     0      2
    #> RED:GREEN         0   1     1      1
    #> BLUE              1   0     0      1
    #> BLUE:GREEN        1   0     1      1
    #> BLUE:RED          1   1     0      2
    #> BLUE:RED:GREEN    1   1     1      1

根据此answer,在venn中还有许多用于R图的软件包。

例如,VennDiagram::venn.diagram包具有na变量,该变量获取stopremovenone。因此,这里我们将使用remove;但是,它只会提供图表而不是表格。您可以在其他软件包中探索其他可能性。

08-24 12:51
查看更多