r - 在小标题中查找行最小值和列索引
问题描述
我有以下小标题:
> df <- tibble(
ID = LETTERS[1:4],
a = c(1,5,9,8),
b = c(5,9,8,2),
c = c(5,4,5,5)
)
> df
# A tibble: 4 x 4
ID a b c
<chr> <dbl> <dbl> <dbl>
1 A 1 5 5
2 B 5 9 4
3 C 9 8 5
4 D 8 2 5
>
我想要的是从该最小值中获取列的行最小值以及a:c
列索引。
输出表应如下所示:
# A tibble: 4 x 6
ID a b c Min Col_Index
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A 1 5 5 1 1
2 B 5 9 4 4 3
3 C 9 8 5 5 3
4 D 8 2 5 2 2
我不想用rowwise()
!
谢谢!
解决方案
您可以使用pmin
withdo.call
来获得按行的最小值,并否定要使用的值来max.col
获得最小值的列索引。
library(dplyr)
library(purrr)
df %>%
mutate(Min = do.call(pmin, select(., a:c)),
Col_Index = max.col(-select(., a:c)))
# ID a b c Min Col_Index
# <chr> <dbl> <dbl> <dbl> <dbl> <int>
#1 A 1 5 5 1 1
#2 B 5 9 4 4 3
#3 C 9 8 5 5 3
#4 D 8 2 5 2 2
使用purrr
's pmap_dbl
:
df %>%
mutate(Min = pmap_dbl(select(., a:c), ~min(c(...))),
Col_Index = pmap_dbl(select(., a:c), ~which.min(c(...))))
推荐阅读
- wso2 - 我如何向 inputHandler 提供输入数据
- cmake - 为什么我需要可分离编译?
- javascript - 将图像 URL 转换为文件 - Javascript
- objective-c - 如何为表格 NSTabViewController 选择选项卡
- sql-server - 在 Visual Studio 2015 中构建 SQL CLR 项目
- ruby-on-rails - Ruby on Rails,图像不加载
- cakephp - cakephp 3中相同外键的一个模型中的多个belongTo关系
- jquery - 将按钮放置在 Kendo Grid 的所有行中的列中
- excel - Power 查询合并表任意对任意
- php - 找不到 torophp 类