This question is really about R syntax and not about the normal distribution or sampling. So I guess it's
'off topic' here, and may be closed.
I'm not quite sure what your difficulty is.
If you set the same seed before each program,
then you should fill an $n\times p$ matrix
by columns with exactly the same normal variates.
n=5; p=2
set.seed(713) # set seed
X = matrix(rnorm(n*p), n, p); X
[,1] [,2]
[1,] -1.5925966 0.37590371
[2,] -0.1458793 0.28096447
[3,] -1.0048927 -0.60433386
[4,] -1.5337787 -0.03059243
[5,] 0.3318419 0.46158609
set.seed(713) # set same seed again
X = matrix(ncol = p, nrow = n)
for (i in 1:p) {
X[, i] = rnorm(n) }
X
[,1] [,2]
[1,] -1.5925966 0.37590371
[2,] -0.1458793 0.28096447
[3,] -1.0048927 -0.60433386
[4,] -1.5337787 -0.03059243
[5,] 0.3318419 0.46158609
But if I've missed the point and you're asking
something else,
then I suggest you replace randomly generated normal variates by sequences of integers. Then the rules
for filling matrices might be clearer to you:
n = 5; p = 2; matrix(1:(n*p),n,p) # n rows, p col
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
n = 5; p = 2
X = matrix(ncol = p, nrow = n)
for (i in 1:p) {
X[, i] = 1:n
}
X
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
[5,] 5 5
When matrix
turns a vector into a matrix, the
default order is to fill the matrix by columns.
(All vectors, unless specifically modified, are considered column vectors, even
if they print out as rows.)
y = 1:10; matrix(y, ncol=2)
[,1] [,2]
[1,] 1 6
[2,] 2 7
[3,] 3 8
[4,] 4 9
[5,] 5 10
y = 1:10; matrix(y, ncol=2, byrow=T)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
You can make row vectors.
w = c(1,2,3,4,3,2) # 'c' for column vector
X = as.matrix(w)
X
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 3
[6,] 2
t(X) # transpose is a row vector
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 3 2
t(X) %*% X # matrix multiplication
[,1]
[1,] 43
X %*% t(X)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 3 2
[2,] 2 4 6 8 6 4
[3,] 3 6 9 12 9 6
[4,] 4 8 12 16 12 8
[5,] 3 6 9 12 9 6
[6,] 2 4 6 8 6 4
X*t(X)
Error in X * t(X) : non-conformable arrays
t(w)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 3 2
t(w)%*%w
[,1]
[1,] 43
set.seed(1); X = matrix(rnorm(n*p), n, p)
and then run the analysis. Thenset.seed(1); X = matrix(ncol = p, nrow = n) for (i in 1:p) { X[, i] = rnorm(n) }
and run the analysis again. You should get same results now $\endgroup$