首页 > 解决方案 > 在小标题中查找行最小值和列索引

问题描述


我有以下小标题:

> 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()

谢谢!

标签: rpurrrtibble

解决方案


您可以使用pminwithdo.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(...))))

推荐阅读