在R中,如何返回一行中的第n个最大数字,并将结果输出到新列,每行重复一次



假设我正试图从指定的列向量(在本例中,从第1列到第4列(中逐行选择第二个最高值。然后,我希望将结果(理想情况下是实际数字(发送到一个新列,称之为Second。我该怎么做?

使用Rfast包的当前代码(我无法破译其文档(:

df$Second <- Rfast::rownth(as.matrix(df[,c(1:4)]), elems=3)

以下是一些示例数据:

df <- structure(list(A = c(-0.113802816901408, -0.613802816901408, 
0.136197183098592, 0.126197183098592, 0.286197183098592), B = c(-0.294595070422536, 
-0.504595070422535, 0.125404929577464, 0.135404929577464, 0.275404929577465
), C = c(-0.277065727699531, -0.507065727699531, 0.282934272300469, 
0.0729342723004693, 0.122934272300469), D = c(-0.222699530516432, 
-0.132699530516432, -0.162699530516432, 0.127300469483568, -0.0126995305164321
), E = c(-0.246845657276995, -0.426845657276995, -0.186845657276995, 
0.133154342723005, 0.113154342723004)), row.names = c(NA, 5L), class = "data.frame")

Rfast::rownth给出n的最小值。对于5列数据帧,第二个最高值是第四个最小值。

n <- 2
Rfast::rownth(as.matrix(df), rep(ncol(df) - n + 1, nrow(df)))
#[1] -0.2226995 -0.4268457  0.1361972  0.1331543  0.2754049

在具有apply:的基础R中

apply(df, 1, function(x) sort(x, decreasing = TRUE)[n])

使用collapse

library(collapse)
n <- 2
dapply(df, function(x) x[radixorder(x, decreasing = TRUE)][n], 
MARGIN = 1) 
#[1] -0.2226995 -0.4268457  0.1361972  0.1331543  0.2754049

或使用fnth

-fnth(-t(df), n)
#       1          2          3          4          5 
#-0.2226995 -0.4268457  0.1361972  0.1331543  0.2754049 

最新更新