检索 R 中列的最大值和第二个最大值的行名

  • 本文关键字:最大值 第二个 检索 r
  • 更新时间 :
  • 英文 :


我们有这个 df

# We create the df
x <- c(1,33,5,2,56,1)
y <- c(4,358,57,3,32,2)
df <- as.data.frame(cbind(x,y))
rownames(df) <- c("a", "b", "c", "d", "e", "f")

df 是:

x    y
a  1    4
b 33  358
c  5   57
d  2    3
e 56   32
f  1    2

我想从列中检索最大值及其第二高值的行名x,并从y列中检索相同的行名。

因此,结果将从xeb,并从ybc

我尝试了这些代码,但没有成功。

rownames(df)[max(df$x)] # for the maximum value
nx <- length(df$x) # length of the x column
rownames(df)[sort(df$x, partial=nx-1)[nx-1]] # for the second max value

但是,前三个代码行的结果是:

NA  # what's wrong?
6   # yeah, it is 6
"e" # nope, the second max is "b"

问题出在哪里,如何解决这些问题?

我们可以遍历列,order递减,使用该索引获取行名,对前两个进行子集

sapply(df, function(x) head(row.names(df)[order(x, decreasing = TRUE)], 2))
#      x   y  
#[1,] "e" "b"
#[2,] "b" "c"

你很接近:只需找到值

rownames(df[df$x == max(df$x),]) # for the maximum value
nx <- length(df$x) # length of the x column
rownames(df[df$x == sort(df$x, partial=nx-1)[nx-1],]) # for the second max value

使用dplyr::filter和基本 Rquantile函数的替代方法。

df %>%  
filter(variable > quantile(.$variable, 0.975, na.rm = T))

最新更新