首页 > 解决方案 > 转换数据框(按计数交叉表)

问题描述

我有一个具有这种结构的 df(来自 csv)

id  att1_beer att1_wine att2_beer att2_wine
1   1         1         0         0
2   0         1         0         1
3   1         1         0         1
4   0         1         0         1
5   1         1         0         0

我想得到一个这种格式的表格(最好是 Tidyverse):

      Beer Wine
Att1   3    5
Att2   0    3

这可能吗?我试图避免导出到 Excel 来做到这一点。

标签: rtidyverse

解决方案


可以重塑为“长”,pivot_longer然后得到sum按组

library(dplyr)
df %>% 
  select(-id) %>%
  pivot_longer(cols =everything(), names_sep="_",
    names_to = c("grp", ".value")) %>% 
  group_by(grp) %>% 
  summarise(across(everything(), sum), .groups = 'drop')

或使用base R

sapply(split.default(df[-1], sub(".*_", "", names(df)[-1])), colSums)

数据

df <- structure(list(id = 1:5, att1_beer = c(1L, 0L, 1L, 0L, 1L), 
att1_wine = c(1L, 
1L, 1L, 1L, 1L), att2_beer = c(0L, 0L, 0L, 0L, 0L), att2_wine = c(0L, 
1L, 1L, 1L, 0L)), class = "data.frame", row.names = c(NA, -5L
))

推荐阅读