why dim of colMeans/rowMeans return null?

感情迁移 提交于 2019-12-11 03:33:21

问题


I am new to R. I have the following code

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)))

and for some reason I get NULL for dimension of row/col means.


回答1:


'as.matrix' turns the vector 'colMeans(x1)' into a matrix. Then the dimensions are 5 and 1, as expected:

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))))

Output:

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

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

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



回答2:


If you really want to coerce a vector into a matrix, you could try something like:

##  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)

Hope that helps...



来源:https://stackoverflow.com/questions/31258101/why-dim-of-colmeans-rowmeans-return-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!