Crawling Antz
Crawling Antz

Reputation: 335

Generate matrix with iid normal random variables using R

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.

Upvotes: 23

Views: 59494

Answers (4)

Guilherme Salome
Guilherme Salome

Reputation: 2039

You can use:

replicate(NumbOfColumns,rnorm(NumbOfLines))

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

Upvotes: 1

Oddsun
Oddsun

Reputation: 1

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!

Upvotes: -3

Macro
Macro

Reputation: 1510

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.

Upvotes: 37

shhhhimhuntingrabbits
shhhhimhuntingrabbits

Reputation: 7475

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

Upvotes: 2

Related Questions