英文:
Variance over a 3D array in R
问题
在处理一个三维数组:
ar3d <- array(floor(100 * runif(100 * 20 * 30)), dim = c(100, 20, 30))
我感到困惑的是:
length(apply(ar3d, MARGIN = 1, FUN = "sd"))
# [1] 100
而
dim(apply(ar3d, MARGIN = 1, FUN = "var"))
# [1] 900 100
如何尽快地计算20 * 30个值之间的方差?
非常感谢!
英文:
Working on a 3d array:
ar3d <- array(floor(100 * runif(100 * 20 * 30)), dim = c(100, 20, 30))
I am confused why
length(apply(ar3d, MARGIN = 1, FUN = "sd"))
# [1] 100
While
dim(apply(ar3d, MARGIN = 1, FUN = "var"))
# [1] 900 100
How can I calculate the variance amongst the 20 * 30 values as fast as possible?
Many thanks
答案1
得分: 2
对于 var
,如果你想获得一个标量而不是协方差矩阵,你应该使用 var(c(x))
,而不是 var(x)
。
当你键入 ?var
时,你会看到:
var、cov 和 cor 计算 x 的方差以及 x 和 y 的协方差或相关性,如果它们是向量的话。如果 x 和 y 是矩阵,那么计算 x 的列与 y 的列之间的协方差(或相关性)。
你可以像这样尝试:
> ar3d <- array(floor(100 * runif(100 * 20 * 30)), dim = c(100, 20, 30))
> length(apply(ar3d, 1, \(x) var(c(x))))
[1] 100
> length(apply(ar3d, 1, var))
[1] 90000
> length(apply(ar3d, 1, sd))
[1] 100
英文:
For var
, you should use var(c(x))
instead of var(x)
if you want to obtain a scalar rather a covariance matrix.
When you type ?var
, you see
> var, cov and cor compute the variance of x and the covariance or
> correlation of x and y if these are vectors. If x and y are matrices
> then the covariances (or correlations) between the columns of x and
> the columns of y are computed.
You can try it out like
> ar3d <- array(floor(100 * runif(100 * 20 * 30)), dim = c(100, 20, 30))
> length(apply(ar3d, 1, \(x) var(c(x))))
[1] 100
> length(apply(ar3d, 1, var))
[1] 90000
> length(apply(ar3d, 1, sd))
[1] 100
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论