如何汇总多列的值?

How to summarize values across multiple columns?

我有一个如下所示的数据框:

1  2  3  4  5

A  B  A  B  A

C  B  B  B  B 

A  C  A  B  B

我想以这样的频率 table 总结我的数据:

   A  B  C
1  2  0  1
2  0  2  1
3  2  1  0
4  0  3  0
5  1  2  0

我怎样才能做到这一点?

您可以使用以下解决方案:

library(tidyr)
library(janitor)

tab %>%
  pivot_longer(everything(), names_to = "nm", values_to = "val", 
               names_prefix = "X") %>%
  tabyl(nm, val)

 nm A B C
  1 2 0 1
  2 0 2 1
  3 2 1 0
  4 0 3 0
  5 1 2 0

你可以使用

library(tidyr)

data %>% 
  pivot_longer(everything()) %>% 
  { table(.$name, .$value) }

哪个returns

    A B C
  1 2 0 1
  2 0 2 1
  3 2 1 0
  4 0 3 0
  5 1 2 0

base Rtable

的选项
table(c(col(df1)),  c(t(df1)))
   
    A B C
  1 2 1 0
  2 1 1 1
  3 0 3 0
  4 1 1 1
  5 1 2 0

数据

df1 <- structure(list(`1` = c("A", "C", "A"), `2` = c("B", "B", "C"), 
    `3` = c("A", "B", "A"), `4` = c("B", "B", "B"), `5` = c("A", 
    "B", "B")), class = "data.frame", row.names = c(NA, -3L))

另一个 table 选项 stack

> t(table(stack(df)))
   values
ind A B C
  1 2 0 1
  2 0 2 1
  3 2 1 0
  4 0 3 0
  5 1 2 0