矩阵中最高值的位置

R18*_*R18 6 r matrix highest indices

假设我们有matrix一个这样的:

# Set seed
  set.seed(12345)
# Generate data.frame  
  df <- matrix(sample(1:100,100), nrow = 10)
Run Code Online (Sandbox Code Playgroud)

我想获取第一个最高值所在的行和列n

我知道使用which(df == max(df), arr.ind=TRUE)我可以得到我想要的东西,但只是为了获得最高的价值。

假设我们想要矩阵中 5 个最高值的位置。根据之前的答案,我尝试过,which(aux %in% sort(df, decreasing=T)[1:5], arr.ind = TRUE)但没有成功。

我还知道,使用 order(df, decreasing=T)和调制结果可以得到我正在寻找的行和列。尽管如此,我认为这应该是获得它的最快方法。

提前谢谢你的帮助

H 1*_*H 1 5

您可以使用match()arrayInd()

vals <- head(sort(df, decreasing = TRUE), 5)

cbind(vals, arrayInd(match(vals, df), dim(df), useNames = TRUE))

     vals row col
[1,]  100   8   3
[2,]   99   9   9
[3,]   98   4   8
[4,]   97   7   9
[5,]   96   3   2
Run Code Online (Sandbox Code Playgroud)


GKi*_*GKi 5

您可以使用quantile

which(df >= quantile(df, 1 - 5/length(df)), arr.ind=TRUE)
#     row col
#[1,]   3   2
#[2,]   8   3
#[3,]   4   8
#[4,]   7   9
#[5,]   9   9
Run Code Online (Sandbox Code Playgroud)

如果存在相同的值,则结果不必是 5。

i <- which(df >= quantile(df, 1 - 5/length(df)))
arrayInd(i[order(df[i], decreasing = TRUE)][1:5], dim(df))
#     [,1] [,2]
#[1,]    8    3
#[2,]    9    9
#[3,]    4    8
#[4,]    7    9
#[5,]    3    2
Run Code Online (Sandbox Code Playgroud)

也许使用 tdigest 可以加快分位数的搜索速度。

或者使用headoforder并使用%%and %/%

. <- head(order(df, decreasing = TRUE), 5) - 1
cbind(. %% dim(df)[[1]], . %/% dim(df)[[1]]) + 1
#     [,1] [,2]
#[1,]    8    3
#[2,]    9    9
#[3,]    4    8
#[4,]    7    9
#[5,]    3    2
Run Code Online (Sandbox Code Playgroud)

或者用 转换索引arrayInd

arrayInd(head(order(df, decreasing = TRUE), 5), dim(df))
#     [,1] [,2]
#[1,]    8    3
#[2,]    9    9
#[3,]    4    8
#[4,]    7    9
#[5,]    3    2
Run Code Online (Sandbox Code Playgroud)

也许使用一些外部库可以帮助加快速度,例如collapse::radixorderv.

. <- head(collapse::radixorderv(df, decreasing = TRUE), 5) - 1
cbind(. %% dim(df)[[1]], . %/% dim(df)[[1]]) + 1
Run Code Online (Sandbox Code Playgroud)