Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate matrix with iid normal random variables using R

Tags:

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.

like image 957
Crawling Antz Avatar asked Jul 24 '12 22:07

Crawling Antz


3 Answers

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.

like image 64
Macro Avatar answered Sep 26 '22 15:09

Macro


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

like image 33
shhhhimhuntingrabbits Avatar answered Sep 23 '22 15:09

shhhhimhuntingrabbits


You can use:

replicate(NumbOfColumns,rnorm(NumbOfLines))

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

like image 37
Guilherme Salomé Avatar answered Sep 22 '22 15:09

Guilherme Salomé