[英]In R, how to return the nth largest number in a row and output result to a new column, repeated for every row?
Let's say I am trying to select the 2nd highest value row-wise from a specified vector of columns (in this example, from columns 1 through 4).假设我正在尝试 select 从指定的列向量(在本例中,从列 1 到 4)按行排列第二高值。 I then want the result (ideally, the actual number) to be sent to a new column, let's call it Second
.然后我希望将结果(理想情况下是实际数字)发送到一个新列,我们称之为Second
。 How might I do this?我该怎么做?
Current code using the Rfast
package (the documenatation of which I can't decipher):使用Rfast
package 的当前代码(我无法破译的文档):
df$Second <- Rfast::rownth(as.matrix(df[,c(1:4)]), elems=3)
Here are some example data:以下是一些示例数据:
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
gives the n
th smallest value. Rfast::rownth
给出第n
个最小值。 2nd highest value is 4th smallest value for a 5 column dataframe.第二个最大值是 5 列 dataframe 的第四个最小值。
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
In base R with apply
:在基础 R 中apply
:
apply(df, 1, function(x) sort(x, decreasing = TRUE)[n])
Using collapse
使用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
Or use fnth
或使用fnth
-fnth(-t(df), n)
# 1 2 3 4 5
#-0.2226995 -0.4268457 0.1361972 0.1331543 0.2754049
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.