为什么 colMeans/rowMeans return 为空?

why dim of colMeans/rowMeans return null?

我是 R 新手,我有以下代码

sigma1  = matrix(c(2,0,0,1),2,2)
mu1     = matrix(c(0,10),2,1)

x1      = t(mvrnorm(n = 5, mu1, sigma1))

print(rowMeans(x1))
print(dim(colMeans(x1)))

出于某种原因,我得到 NULL 的维度 row/col 意味着。

如果你真的想将向量强制转换为矩阵,你可以尝试类似的方法:

##  Initial Computations.
sigma1  = matrix(c(2,0,0,1),2,2)
mu1 = matrix(c(0,10),2,1)
x1 = t(mvrnorm(n = 5, mu1, sigma1))

##  Coerce the vector of colMeans into a 1 by 5 matrix.
colmeans.x1 = rbind(colMeans(x1))

##  Inspect the dimensions of the matrix created above.
dim(colmeans.c1)

希望对您有所帮助...

'as.matrix' 将向量 'colMeans(x1)' 转换为矩阵。那么维度就是5和1,符合预期:

library(rockchalk)

sigma1  = matrix(c(2,0,0,1),2,2)
mu1     = matrix(c(0,10),2,1)
x1      = t(mvrnorm(n = 5, mu1, sigma1))

print(rowMeans(x1))
print(dim(colMeans(x1)))
print(dim(as.matrix(colMeans(x1))))

输出:

> print(rowMeans(x1))
[1] -0.1518187  9.4232239

> print(dim(colMeans(x1)))
NULL

> print(dim(as.matrix(colMeans(x1))))
[1] 5 1
>