[英]Compute element-wise quantiles for a list of matrices R
I have a list of matrices that looks like this:我有一个矩阵列表,如下所示:
matrix.list <- list()
for(i in 1:1000){
matrix.list[[i]] <- matrix(rnorm(9), ncol=3, nrow=3)
}
I can calculate element wise means and standard deviations in a straightforward way, following this stackoverflow question :我可以按照这个 stackoverflow 问题,以一种直接的方式计算元素均值和标准差:
matrix.mean <- apply(simplify2array(matrix.list), 1:2, mean)
matrix.sd <- apply(simplify2array(matrix.list), 1:2, sd )
However, I would like to calculate the 0.025 and 0.975 quantiles.但是,我想计算 0.025 和 0.975 分位数。 I would do this on a vector like this:
我会在这样的向量上执行此操作:
my.vec <- rnorm(1000)
q.0.025 <- quantile(my.vec, probs = 0.025)
q.0.975 <- quantile(my.vec, probs = 0.975)
But how can I calculate these element-wise quantiles across my list of matrices, similar to what I can do for mean and sd?但是,我如何在我的矩阵列表中计算这些元素分位数,类似于我可以为 mean 和 sd 做的事情? As soon as I pass parameters to function
apply
it fails.一旦我将参数传递给函数
apply
它就会失败。
Q <- apply(simplify2array(matrix.list), 1:2, quantile, prob = c(0.025, 0.975))
apply
would simplify the result to an array, and since the function quantile
returns more than one values, you have a 3D array. apply
会将结果简化为数组,并且由于函数quantile
返回多个值,因此您有一个 3D 数组。 But extraction is straightforward:但是提取很简单:
Q[1, , ] ## 0.025 quantile
# [,1] [,2] [,3]
#[1,] -2.046691 -1.925256 -2.075718
#[2,] -1.981182 -1.999648 -1.887588
#[3,] -1.931738 -1.743275 -1.854083
Q[2, , ] ## 0.975 quantile
# [,1] [,2] [,3]
#[1,] 1.953820 2.042508 1.836591
#[2,] 2.065854 2.006068 1.899495
#[3,] 1.885080 2.021729 1.943645
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.