r - 按组汇总值,但保留原始数据
问题描述
我试图弄清楚如何将values
属于category
a 和 b 的因子相加file
,但还要保留原始数据。
library(dplyr)
df <- data.frame(ID = 1:20, values = runif(20), category = rep(letters[1:5], 4), file = as.factor(sort(rep(1:5, 4))))
ID values category file
1 1 0.65699229 a 1
2 2 0.70506478 b 1
3 3 0.45774178 c 1
4 4 0.71911225 d 1
5 5 0.93467225 e 1
6 6 0.25542882 a 2
7 7 0.46229282 b 2
8 8 0.94001452 c 2
9 9 0.97822643 d 2
10 10 0.11748736 e 2
11 11 0.47499708 a 3
12 12 0.56033275 b 3
13 13 0.90403139 c 3
14 14 0.13871017 d 3
15 15 0.98889173 e 3
16 16 0.94666823 a 4
17 17 0.08243756 b 4
18 18 0.51421178 c 4
19 19 0.39020347 d 4
20 20 0.90573813 e 4
以便
df[1,2]
将添加到文件 1df[2,2]
的类别中'ab'
df[6,2]
将添加到 文件 2df[7,2]
的类别中'ab'
- 等等
到目前为止,我有这个:
df %>%
filter(category %in% c('a' , 'b')) %>%
group_by(file) %>%
summarise(values = sum(values))
问题
我想将求和值的类别更改为“ab”并将其附加到同一管道中的原始数据帧。
期望的输出:
ID values category file
1 1 0.65699229 a 1
2 2 0.70506478 b 1
3 3 0.45774178 c 1
4 4 0.71911225 d 1
5 5 0.93467225 e 1
6 6 0.25542882 a 2
7 7 0.46229282 b 2
8 8 0.94001452 c 2
9 9 0.97822643 d 2
10 10 0.11748736 e 2
11 11 0.47499708 a 3
12 12 0.56033275 b 3
13 13 0.90403139 c 3
14 14 0.13871017 d 3
15 15 0.98889173 e 3
16 16 0.94666823 a 4
17 17 0.08243756 b 4
18 18 0.51421178 c 4
19 19 0.39020347 d 4
20 20 0.90573813 e 4
21 21 1.25486225 ab 1
22 22 1.87216325 ab 2
23 23 1.36548126 ab 3
解决方案
这将为您提供结果
df %>% bind_rows(
df %>%
filter(category %in% c('a' , 'b')) %>%
group_by(file) %>%
mutate(values = sum(values), category = paste0(category,collapse='')) %>%
filter(row_number() == 1 & n() > 1)
) %>% mutate(ID = row_number())
顺便说一句,代码专业人士在示例中生成的数据框是这个:
df <- data.frame(ID = 1:20, values = runif(20), category = rep(letters[1:5], 4), file = as.factor(sort(rep(1:4, 5))))
现在假设您要对多列求和,您需要在向量中提供列表:
cols = c("values") # columns to be sum
df %>% bind_rows(
df %>%
filter(category %in% c('a' , 'b')) %>%
group_by(file) %>%
mutate_at(vars(cols), sum) %>%
mutate(category = paste0(category,collapse='')) %>%
filter(row_number() == 1 & n() > 1)
) %>% mutate(ID = row_number())
推荐阅读
- bash - Bash sed awk,从 /proc/cpuinfo 和 /proc/meminfo 格式化 CPU/Mem 信息
- c# - SqlException (0x80131904): 无法打开备份设备操作系统错误5(拒绝访问。)
- c++ - 在 C++ 中将连续范围映射到离散箱中
- excel - EXCEL:如果column_A中的单元格包含column_C中的单词,则将单词插入它旁边(来自column_D)INTO B
- angular - TypeError:无法读取茉莉花中未定义的属性“客户端”
- spring-boot - 对多个消息使用者使用手动提交
- html - 如何使用 Vue draggable 将组件列表中的项目拖动到另一个组件中的列表?
- ios - 请求的身份验证范围不足 Google Sheets API Swift
- flutter - Flutter 在网格视图中增加容器高度
- typescript - 类型“字符串”不可分配给类型“ImageSourcePropType”