r - 在数据框中查找第二个最小值的索引
问题描述
我有一个数据框 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
解决方案
你可以做 :
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
推荐阅读
- database - How should I design my relational tables?
- javascript - 在按钮上使用 Jquery 模拟键盘
- wpf - 如何将 UserControl 中的数据或与属性通信设置为新窗口?
- reactjs - 反应状态改变而不是重新渲染孩子
- matlab - 如何用来自其他两个第一维和第二维不相等的 3d 数组的内容填充 3d 数组
- excel - 将 selenium vba 代码转换为 xmlhttp 获取请求
- java - ArrayList remove 函数删除错误的对象
- php - Reddit POST 请求 - 错误 403 (php/curl)
- laravel-5 - 什么时候不应该使用多态关系?
- javascript - 在 for 循环中使用 d3