r - 如何使用 dplyr 从每一行中获取最大的列值
问题描述
鉴于以下数据:
df <- data.frame(
a = c(1,2,3,5),
b = c(7,9,52,4),
c = c(53, 11,22,1),
d = c("something","string","another", "here")
)
看起来像:
a b c d
1 1 7 53 something
2 2 9 11 string
3 3 52 22 another
4 5 4 1 here
我想使用 dplyr 创建列“max”,其中max
是最大行值的列。
所以对于上述我会
a b c d max
1 1 7 53 something c
2 2 9 11 string c
3 3 52 22 another b
8 5 4 1 here a
解决方案
我们可以使用max.col
查找每行最大值的列索引,使用它来获取列名并分配 ass 'max' 列
df['max'] <- names(df)[1:3][max.col(df[1:3], "first")]
df
# a b c d max
#1 1 7 53 something c
#2 2 9 11 string c
#3 3 52 22 another b
#4 5 4 1 here a
使用tidyverse
,另一种方法是重塑为“长”格式,然后找到max
library(dplyr)
library(tidyr)
df %>%
mutate(ind = row_number()) %>%
select(-d) %>%
pivot_longer(cols = a:c) %>%
group_by(ind) %>%
slice(which.max(value)) %>%
select(-value) %>%
pull(name) %>%
mutate(df, max = .)
或与pmap
library(purrr)
df %>%
mutate(max = pmap_chr(select(., a:c), ~ c(...) %>%
which.max %>%
names ))
推荐阅读
- pandas - 通过使用 pandas 将定义的条件与输入列进行比较,在数据集中追加一个空的输出列
- google-apps-script - 使用 Google 应用脚本在 Google 表格中创建宏
- webpack - 使用 customize-cra 从 node_modules 中的 bundle.js 中删除包
- node.js - 在 mongoose 聚合中修改 $cond 的结果值?
- python - 无法为 Python 安装 Kivy
- kotlin - 调试 Kotlin 符号处理 (KSP)
- mysql - 如何使用条件创建有效的 SQL 触发器?
- reactjs - 将 onClick 与 React 组件一起使用,可点击组件边界与浏览器上的可见位置不匹配
- swift - 后退按钮色调颜色
- python - python - 如何使用python中的haversine库计算大距离矩阵?