我需要在第三个轴上排列数组的值。我有一个像这样的数组:
a <- array(c(1:9,11:19,21:29),dim = c(3,3,3))
预期结果是一个矩阵,该矩阵具有第一个矩阵的秩,我希望像这样计算:apply(X = a, MARGIN = c(1,2), FUN = rank)[, ,1]
# expected result because a[,,1] is the minimal value of my array
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
但是apply
函数返回另一个数组,这很奇怪,因为当我使用mean
,max
或sort
等其他函数时,它返回一个矩阵。
我检查了apply(a, c(1,2), print)
并打印了我感兴趣的矢量(例如,它在第一次迭代中打印了1 11 21
)。
我可以使用for循环对此进行编码,但至少我对这种情况下的确切问题感到好奇。
# The for loop to obtain the good result
a2 <- a[,,1]
for(i in seq(dim(a)[1])){
for(j in seq(dim(a)[2])){
a2[i,j] <- rank(a[i,j,])[1]
}
}
提前感谢!
尝试
apply(a, c(1,2), function(x) rank(x)[1])
# [,1] [,2] [,3]
# [1,] 1 1 1
# [2,] 1 1 1
# [3,] 1 1 1
您可以使用[1,,]
代替[,,1]
,即>]
apply(X = a, MARGIN = c(1,2), FUN = rank)[1,,]
诸如此类
> apply(X = a, MARGIN = c(1,2), FUN = rank)[1,,]
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1