22

Is there a way to generate a data set with normally distributed random values in R without using a loop? Each entry would represent an independent random variable with a normal distribution.

Crawling Antz
  • 325
  • 1
  • 2
  • 6

4 Answers4

35

To create an N by M matrix of iid normal random variables type this:

matrix( rnorm(N*M,mean=0,sd=1), N, M) 

tweak the mean and standard deviation as desired.

Macro
  • 1,450
  • 1
  • 10
  • 18
  • 1
    As long as the questioner understands that N is the number of rows and M the number of columns, then he will be well served by this answer – IRTFM Jul 24 '12 at 23:26
  • @DWin, agreed. That is the conventional notation when referring to matrices in any context though, right? – Macro Jul 24 '12 at 23:26
  • I'm not really sure. I do know that people sometimes express surprise at the fact that R's matrices are filled in column-major order with calls to `matrix` unless byrow=TRUE. Ihat made me think that there might be variation in matrix conventions across various languages. – IRTFM Jul 24 '12 at 23:30
  • for `matrix` you can specify one of `nrow` or `ncol` – qwr May 01 '21 at 07:39
2

let mu be a vector of means and sigma a vector of standard devs

mu<-1:10
sigma<-10:1
sample.size<-100
norm.mat<-mapply(function(x,y){rnorm(x,y,n=sample.size)},x=mu,y=sigma)

would produce a matrix with columns holding the relevant samples

shhhhimhuntingrabbits
  • 7,397
  • 2
  • 23
  • 23
1

You can use:

replicate(NumbOfColumns,rnorm(NumbOfLines))

You can replace rnorm with other distribution function, for example runif, to generate matrices with other distributions.

Guilherme Salomé
  • 1,899
  • 4
  • 19
  • 39
-3

Notice: each entry is independent. So you cannot avoid using for loops, because you have to call rnorm once for each independent variable. If you just call rnorm(n*m) that's the n*m samples from the same random variable!

Oddsun
  • 1
  • this is wrong, and confusing ... `rnorm(n*m)` *does* generate `n*m` **independent** random samples, exactly as the OP requested. – Ben Bolker Apr 11 '13 at 19:38