r函数类似于pmin(),但发现跨数据框架列的第n个最低值?



我想要一个函数,可以找到跨列的第n个最小值。换句话说,这是一个类似于pmin()的函数,但我希望它返回的不是最小值,而是第n个最小值。提前感谢!

df %>%
rowid_to_column() %>%
pivot_longer(-rowid)%>%
arrange(value)%>% #You could arrange with decreasing to find max
group_by(rowid) %>%
summarise(value = nth(value, 2)) # Find the second minimum
# A tibble: 10 x 2
rowid   value
<int>   <dbl>
1     1 -0.560 
2     2 -0.218 
3     3  0.401 
4     4  0.0705
5     5 -0.556 
6     6  1.72  
7     7  0.498 
8     8 -1.27  
9     9 -0.687 
10    10 -0.446 

这是一个简单的例子(可以修改它来处理NAs):

nth_lowest <- function(x,n) x[order(x)[n]]

应用于数据帧,使用dplyr包中的rowwise()c_across()

df %>%
rowwise() %>%
mutate( second_lowest = f(c_across(x:z),2))

输出:

x      y      z second_lowest
<dbl>  <dbl>  <dbl>         <dbl>
1 -0.560   1.22  -1.07        -0.560 
2 -0.230   0.360 -0.218       -0.218 
3  1.56    0.401 -1.03         0.401 
4  0.0705  0.111 -0.729        0.0705
5  0.129  -0.556 -0.625       -0.556 
6  1.72    1.79  -1.69         1.72  
7  0.461   0.498  0.838        0.498 
8 -1.27   -1.97   0.153       -1.27  
9 -0.687   0.701 -1.14        -0.687 
10 -0.446  -0.473  1.25        -0.446 

输入:

set.seed(123)
df <- data.frame(x=rnorm(10), y=rnorm(10), z=rnorm(10))

对于pmapnth也可以这样做

library(purrr)
library(dplyr)
pmap_dbl(df, ~ nth(sort(c(...)), n = 2))

最新更新