宽到长的二进制矩阵相加计数

Wide to long binary matrix adding counts

我想从宽格式转到长格式,但保留计数值并对列进行分解。我有这个:

variable   LF1   LF2   LF3   LF4   LF5   Counts
A           1     0     0     0     0      5 
A           1     0     1     0     0      1    
B           1     0     0     1     0      3 
B           1     0     0     0     1      2 
B           1     0     0     0     0      1 
C           1     0     0     0     0      8 
D           1     1     0     0     0      6 
D           1     0     1     0     0      4

我想要以下内容:

 variable   factor    count
    A         F1        6
    A         F3        1
    B         F1        6
    B         F4        3
    B         F5        2
    C         F1        8
    D         F1        10
    D         F2        6
    D         F3        4

这意味着数据在对计数求和的同时 t运行 变长。 我在 reshape2 中尝试了所有我能想到的组合,但我 运行 没有想法,例如

data_grouped <- reshape2::melt(data, id.vars=c("variable"))
data_grouped <- reshape2::melt(data, id.vars=c("variable","LF1","LF2","LF3","LF4","LF5"))

我还看到我可以通过连接以下内容得到类似的东西:

data %>% group_by(variable, LF1) %>% summarise(sum(counts))
data %>% group_by(variable, LF2) %>% summarise(sum(counts))

但这是非常低效的,不是理想的解决方案,因此我非常感谢您的帮助。

假设您的数据名为 df:

library(tidyverse)
df %>%
  pivot_longer(cols = starts_with("LF"),
               names_to = "factor") %>%
  filter(value == 1) %>%
  group_by(variable, factor) %>%
  summarize(count = sum(Counts)) %>%
  mutate(factor = str_remove(factor, "L")) %>%
  ungroup()

给出:

# A tibble: 9 x 3
  variable factor count
  <chr>    <chr>  <int>
1 A        F1         6
2 A        F3         1
3 B        F1         6
4 B        F4         3
5 B        F5         2
6 C        F1         8
7 D        F1        10
8 D        F2         6
9 D        F3         4