如何获得矩阵列表中每个元素的百分位数

时间:2021-07-11 14:31:27

If I have a list of matrices with same dimensions, how can I get each element of list of matrices in R? For example, I have 4 matrices:

如果我有一个具有相同维度的矩阵列表,我怎样才能得到R中矩阵列表的每个元素?例如,我有4个矩阵:

> a
           [,1]       [,2]       [,3]
[1,] -0.8761453  0.2821336 -0.8541406
[2,] -0.9649200  1.7734091 -1.2058440
[3,] -0.4250063 -0.8197162 -1.3997540
> b
           [,1]       [,2]       [,3]
[1,] -1.2096577 -0.5440074  0.6102016
[2,] -0.1299645 -0.8943189 -1.8042720
[3,]  1.0111488  0.2547343  0.2395172
> c
           [,1]       [,2]       [,3]
[1,]  0.2853833 -0.2716714  0.2330467
[2,] -0.7963095 -1.2120779  0.6909755
[3,]  0.3479346  0.1803124 -0.7400176
> d
             [,1]       [,2]       [,3]
[1,] -1.048740842 -1.0492152 -0.6889409
[2,] -0.004154795 -0.6167335 -0.8028550
[3,] -1.111915258 -2.1586534 -0.1448612

The result I want is if I want the 2nd least minimum of each element.

我想要的结果是如果我想要每个元素的第二最小值。

> res
           [,1]       [,2]       [,3]
[1,] -1.0487408 -0.5440074 -0.6889409
[2,] -0.7963095 -0.8943189 -1.2058440
[3,] -0.4250063 -0.8197162 -0.7400176

1 个解决方案

#1


2  

If we need the second minimum value, create an array by concatenating the matrixes together, specify the dimensions and use apply with the required MARGIN, sort the elements from smallest to largest and get the second element

如果我们需要第二个最小值,通过将矩阵连接在一起来创建一个数组,指定维度并使用apply和所需的MARGIN,将元素从最小值排序到最大值并获取第二个元素

apply(array(c(a, b, c, d), c(dim(a), 4)), c(1, 2), FUN = function(x) sort(x)[2])
#           [,1]       [,2]       [,3]
#[1,] -1.0487408 -0.5440074 -0.6889409
#[2,] -0.7963095 -0.8943189 -1.2058440
#[3,] -0.4250063 -0.8197162 -0.7400176

NOTE: Based on the OP's post, it looks like 'a', 'b', 'c', 'd' are separate matrix objects in the global environment

注意:根据OP的帖子,它看起来像'a','b','c','d'是全球环境中的独立矩阵对象

#1


2  

If we need the second minimum value, create an array by concatenating the matrixes together, specify the dimensions and use apply with the required MARGIN, sort the elements from smallest to largest and get the second element

如果我们需要第二个最小值,通过将矩阵连接在一起来创建一个数组,指定维度并使用apply和所需的MARGIN,将元素从最小值排序到最大值并获取第二个元素

apply(array(c(a, b, c, d), c(dim(a), 4)), c(1, 2), FUN = function(x) sort(x)[2])
#           [,1]       [,2]       [,3]
#[1,] -1.0487408 -0.5440074 -0.6889409
#[2,] -0.7963095 -0.8943189 -1.2058440
#[3,] -0.4250063 -0.8197162 -0.7400176

NOTE: Based on the OP's post, it looks like 'a', 'b', 'c', 'd' are separate matrix objects in the global environment

注意:根据OP的帖子,它看起来像'a','b','c','d'是全球环境中的独立矩阵对象