r - dplyr:根据匹配的行添加数字
问题描述
假设我有
> fig
hands imp_spe n
1 A 0 39
2 A 1 32
3 B 0 3
4 B 1 2
5 C 0 115
6 C 1 24
7 D 0 11
8 D 1 3
我想添加一个新列fig$new
,在 中添加数字fig$n
,但仅在中的行fig$hands
匹配时。
我需要保持数据框原样。
预期产出
> fig
hands imp_spe n new
1 A 0 39 71
2 A 1 32 71
3 B 0 3 5
4 B 1 2 5
5 C 0 115 139
6 C 1 24 139
7 D 0 11 14
8 D 1 3 14
我正在寻找解决方案dplyr
fig <- structure(list(hands = c("A", "A", "B", "B", "C", "C", "D", "D"
), imp_spe = c(0, 1, 0, 1, 0, 1, 0, 1), n = c(39L, 32L, 3L, 2L,
115L, 24L, 11L, 3L)), row.names = c(NA, -8L), class = "data.frame")
解决方案
干得好
library(dplyr)
fig %>%
group_by(hands) %>%
mutate(new = sum(n)) %>%
ungroup
推荐阅读
- python - 我无法在 python 上安装 nmap 模块
- amazon-web-services - URL中的特殊字符导致403
- r - 当列表嵌套在 R 列表中时,如何简洁地将多个列表的所有元素命名为相同?
- node.js - 内部版本号或最近提交 # 与 AWS CodePipeline node.js
- c# - 导航到上一页
- android - 如何为可穿戴回收站视图创建适配器?
- python - 反转变量矩阵
- c++ - 堆栈和堆内存在计算机内存中的物理位置
- google-bigquery - 基于键在 bigquery 表中创建去重视图
- nestjs - 如何让 Inner Join 在 TypeORM 上工作?