问题
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