r - Select top value within group return all
问题描述
Using the following data frame
df <- data.frame(id = c('A', 'A', 'A', 'B', 'B', 'B', 'B'),
gender = c('M', 'M', 'M', 'F', 'F', 'F', 'F'),
index = c(1, 2, 3, 1, 2, 3, 4))
And I need to take the max value of index
with each id
so I was thinking top_n
function would work but I actually need the max value to be repeated for each id. So something like this is the result I need:
df_result <- data.frame(id = c('A', 'A', 'A', 'B', 'B', 'B', 'B'),
gender = c('M', 'M', 'M', 'F', 'F', 'F', 'F'),
index = c(1, 2, 3, 1, 2, 3, 4),
max_index = c(3, 3, 3, 4 ,4, 4, 4))
Is there something other than top_n
that I can use, or use it but have it repeat?
解决方案
I hope this is what you are looking for:
library(dplyr)
df %>%
group_by(id) %>%
mutate(max_index = max(index))
# A tibble: 7 x 4
# Groups: id [2]
id gender index max_index
<chr> <chr> <dbl> <dbl>
1 A M 1 3
2 A M 2 3
3 A M 3 3
4 B F 1 4
5 B F 2 4
6 B F 3 4
7 B F 4 4
推荐阅读
- c - 如果我需要在锁定互斥锁后解锁它,我该如何返回一个值?
- c - C中的文件重定向
- c# - 在我的脚本中滑动控件在 c# unity3d 中没有按预期工作
- spring - 在 Spring JPA 查询中按活动状态过滤
- visual-studio - 在 Visual Studio 中导出和导入现有 Azure 函数到 Azure Devops
- spring-boot - 会话劫持:当 JSESSIONID cookie 从一个浏览器复制到另一个浏览器时,如何防止访问 Web 应用程序?
- javascript - 当图表 js 中的某些项目没有可用值时显示“NO DATA”消息
- python - FastAPI 招摇不使用自定义标头
- api - 通过 UI 为 webhook 创建自定义 JSON 正文
- html - 如何水平对齐不同元素中的按钮