【问题标题】:Finding the index for 2nd Min value in a data frame在数据框中查找第二个最小值的索引
【发布时间】:2021-03-25 16:19:40
【问题描述】:

我有一个数据框 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

【问题讨论】:

  • 检查y 的输出 - 似乎应该是13,(或两者?),而不是2

标签: r


【解决方案1】:

更新答案

您可以使用factor 编写如下函数:

which_min <- function(x, pos) {
  sapply(x, function(y) {
    which(as.numeric(factor(y, sort(unique(y)))) == pos)[1]
  })
}

which_min(df1, 2)
# x y z 
# 2 2 3 

用其他数据测试它:

df2 <- df1
df2$new <- c(1, 1, 1, 2, 3)
which_min(df2, 2)
#   x   y   z new 
#   2   2   3   4 

原答案

您可以使用order,而不是sort

sapply(df1, function(x) order(unique(x))[2])
# x y z 
# 2 2 3

或者您可以使用sort 中的index.return 参数:

sapply(df1, function(x) sort(unique(x), index.return = TRUE)$ix[2])
# x y z 
# 2 2 3

【讨论】:

  • 如果我的 x 是 c( 1,1,1,2,3) 而 y 和 z 保持不变,是否有可能得到 x 的第二个最小值为 4 的结果?
【解决方案2】:

你可以这样做:

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

【讨论】:

    【解决方案3】:

    另一个使用rank的基本R版本

    > sapply(df1, function(x) which(rank(unique(x)) == 2))
    x y z
    2 2 3
    

    【讨论】:

      【解决方案4】:

      你可以试试这样的:

      sort(unique(unlist(df1)))[2]
      

      【讨论】:

        猜你喜欢
        • 2018-04-22
        • 2017-09-19
        • 1970-01-01
        • 2018-05-20
        • 2022-01-22
        • 2018-03-23
        • 1970-01-01
        • 2017-09-25
        • 1970-01-01
        相关资源
        最近更新 更多