在R中计算3D数组的方差。

huangapple go评论48阅读模式
英文:

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 &lt;- array(floor(100 * runif(100 * 20 * 30)), dim = c(100, 20, 30))

I am confused why

length(apply(ar3d, MARGIN = 1, FUN = &quot;sd&quot;))
# [1]&#160;100

While

dim(apply(ar3d, MARGIN = 1, FUN = &quot;var&quot;))
# [1]&#160;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

&gt; ar3d &lt;- array(floor(100 * runif(100 * 20 * 30)), dim = c(100, 20, 30))

&gt; length(apply(ar3d, 1, \(x) var(c(x))))
[1] 100

&gt; length(apply(ar3d, 1, var))
[1] 90000

&gt; length(apply(ar3d, 1, sd))
[1] 100

huangapple
  • 本文由 发表于 2023年7月10日 14:29:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定