我的数组是
x <- array(1:24, dim=c(3,4,3))我的任务1是根据前两个维度找到最大值
My task 1 is to find the max value according to the first two dimensions
x.max <- apply(x,c(1,2), function(x) ifelse(all(is.na(x)), NA, max(x, na.rm = TRUE)))如果有NA数据 我的任务2是在第三维上找到最大值位置. 我尝试过
in case there is NA data my task 2 is to find the max value position on the third dimension. I tried
x.max.position = apply(x, c(1,2),which.max(x))但这只给了我在拳头两个维度上的位置.
But this only give me the position on the fist two dimensions.
有人可以帮助我吗?
推荐答案目前尚不完全清楚,但是如果您要为每个三维维度的矩阵找到max(那是技术上正确的说法吗? ),那么您需要在第三维中使用apply. ?apply下的参数margin指出:
It's not totally clear, but if you want to find the max for each matrix of the third dimension (is that even a technically right thing to say?), then you need to use apply across the third dimension. The argument margin under ?apply states that:
一个给出下标的向量,该函数将被应用到下标.例如,对于矩阵,1表示行,2表示列,c(1,2)表示行和列.
a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates rows, 2 indicates columns, c(1, 2) indicates rows and columns.
因此,对于具有3D数组的示例,3是第三维.所以...
So for this example where you have a 3D array, 3 is the third dimension. So...
t( apply( x , 3 , function(x) which( x == max(x) , arr.ind = TRUE ) ) ) [,1] [,2] [1,] 3 4 [2,] 3 4 [3,] 3 4这将返回一个矩阵,其中每行包含第三个维度的每个2D数组/矩阵的最大值的行和列索引.
Which returns a matrix where each row contains the row and then column index of the max value of each 2D array/matrix of the third dimension.
如果希望在所有维度上使用max,则可以使用which和arr.ind参数,如下所示:
If you want the max across all dimensions you can use which and the arr.ind argument like this:
which( x==max(x,na.rm=T) , arr.ind = T ) dim1 dim2 dim3 [1,] 3 4 2告诉我们max的值是第三行,第四列,第二个矩阵.
Which tells us the max value is the third row, fourth column, second matrix.
要找到第3点的位置,第1点和第2点的值最大,请尝试:
To find the position at dim 3 where where values on dim 1 and 2 are max try:
which.max( apply( x , 3 , max ) ) # [1] 2告诉我们,三维的第2个位置包含最大值.
Which tells us that at position 2 of the third dimension contains the maximal value.
更多推荐
如何识别数组中最大值的位置?
发布评论