Search code examples
rrandomsimulatorsample

random samples in R


I'm trying to generate 1000 random samples of length 100 from a normal distribution in R. I feel this should be very straight forward, but I can't get it.

for (i in 1:1000) {
  x[i]=rnorm(100, mean=1, sd=1)
}

for (i in 1:1000) {
  y[i]=rnorm(100, mean=1, sd=1)
}

But this code tells me that object x is not found (same thing for y)

Any ideas how to fix it? In the end, I'd like to have two matrices, x and y, where there each column is a random vector

Thanks


Solution

  • Create a vector of random numbers with as many elements as in the matrix (number of rows x number of columns). Use that to construct the matrix, specifying the number of rows (or columns); the matrix() function will infer the number of columns from the length of the vector.

    > nr = 5; nc = 4; matrix(rnorm(nr * nc, mean = 1), nrow = nr)
               [,1]      [,2]      [,3]        [,4]
    [1,]  0.4335546 0.1604642 0.9182186  0.90655887
    [2,]  0.5364028 0.9228126 1.2342502 -1.14907299
    [3,]  2.3253380 0.9264194 4.4438906 -0.12498029
    [4,]  0.4099558 0.7013819 2.3345348  0.03681959
    [5,] -0.6206456 2.3659304 1.8343477  0.61415144