首页 > 解决方案 > 在数据框中查找第二个最小值的索引

问题描述

我有一个数据框 df1。我想从此数据框中找到第二个最小值的索引。使用 which.min 函数我能够获取最小值的行索引,但是有没有办法获取第二最小值的索引?

> df1
structure(list(x = c(1, 2, 3, 4, 3), y = c(2, 3, 2, 4, 6), z = c(1, 
4, 2, 3, 11)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))


 >df1
 x    y    z
 1    2    1
 2    3    4
 3    2    2
 4    4    3
 3    6   11

这是我想要的输出。例如,在 x 中,第 2 行中的值 2 是第二小的值。谢谢你。

>df2
x    2
y    2
z    3

标签: r

解决方案


你可以做 :

sapply(df1, function(x) which.max(x == sort(unique(x))[2]))

#x y z 
#2 2 3 

或与dplyr

library(dplyr)
df1 %>%
  summarise(across(.fns = ~which.max(. == sort(unique(.))[2])))

#      x     y     z
#  <int> <int> <int>
#1     2     2     3

推荐阅读