Generate matrix with iid normal random variables using R

放肆的年华 提交于 2019-11-30 06:24:42

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.

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

You can use:

replicate(NumbOfColumns,rnorm(NumbOfLines))

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

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!