r - 转换数据框(按计数交叉表)
问题描述
我有一个具有这种结构的 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 来做到这一点。
解决方案
可以重塑为“长”,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
))
推荐阅读
- c++ - 将具有空值的字符数组写入文件流
- google-sheets - 带通配符的 VLOOKUP 并找到第 N 次出现?
- sql - Oracle Java Concat Like 带参数
- c - 我的代码不起作用。我的 while 循环有问题
- vue.js - 在由于 VueCLI 想要运行命令“npm run serve”而生成的项目中,我收到一条错误消息“模块构建失败......”
- controller - 如何构建方法来过滤其他参数?
- json - 使用 Circe 自定义编解码器将 json 解码为案例类列表
- azure - 解压后的存档在服务器上不可用
- php - 如何使用 google adsense 或 analytics api 从各个页面获利?
- html - 修复标题重叠页面内容