R 数组中某个维度的最大值和索引?

问题描述 投票:0回答:1

我在 R 中有一个 3 维数组。对于每个切片,我想为切片的每一行找到最大值和最大值的索引。最快的方法是什么?

我已经对每个切片使用 rowMaxs() 来查找按行的最大值,但这并没有给出索引,我需要使用 max.col() 单独获取它。这似乎效率不高。此外,我仍然需要遍历切片,这可能很慢(例如与 C++ 相比)。

我看到有人建议使用 Rcpp,但我已经 20 年没有编写 C++ 代码了,所以想知道现在是否有一个包可以做到这一点。

r arrays max rcpp rcpparmadillo
1个回答
0
投票

如果我理解您的问题,那么您可以使用

apply
生成适当的索引值,然后使用它们从数组中提取适当的值:

set.seed(207)
x <- array(sample(1:24, 24, replace=FALSE), dim=c(2,3,4))

colinds <- apply(x, c(1,3), function(x)which(x==max(x), arr.ind=TRUE))
inds <- cbind(rep(1:nrow(colinds),  ncol(colinds)), c(colinds), rep(1:ncol(colinds), each=nrow(colinds)))
out <- cbind(inds, x[inds])
colnames(out) <- c("row", "col", "face", "max")
out
#>      row col face max
#> [1,]   1   2    1  21
#> [2,]   2   2    1  24
#> [3,]   1   3    2  18
#> [4,]   2   1    2  11
#> [5,]   1   2    3  23
#> [6,]   2   1    3  19
#> [7,]   1   1    4  17
#> [8,]   2   2    4  15

创建于 2023-03-14 与 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.