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.
是否有一种方法可以在不使用循环的情况下生成具有正态分布的随机值的数据集?每个项都表示一个正态分布的独立随机变量。
4 个解决方案
#1
22
To create an N
by M
matrix of iid normal random variables type this:
要创建一个N×M矩阵的iid正常随机变量类型:
matrix( rnorm(N*M,mean=0,sd=1), N, M)
tweak the mean and standard deviation as desired.
根据需要调整平均值和标准偏差。
#2
2
let mu
be a vector of means and sigma
a vector of standard devs
让mu是均值的矢量,是标准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
是否会产生一个包含有相关样本的列的矩阵?
#3
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.
你可以用其他分布函数代替rnorm,例如runif,来生成其他分布的矩阵。
#4
-2
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!
注意:每个条目都是独立的。所以你不能避免使用for循环,因为你必须为每个独立变量调用rnorm。如果你只调用rnorm(n*m)那是来自同一个随机变量的n*m样本!
#1
22
To create an N
by M
matrix of iid normal random variables type this:
要创建一个N×M矩阵的iid正常随机变量类型:
matrix( rnorm(N*M,mean=0,sd=1), N, M)
tweak the mean and standard deviation as desired.
根据需要调整平均值和标准偏差。
#2
2
let mu
be a vector of means and sigma
a vector of standard devs
让mu是均值的矢量,是标准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
是否会产生一个包含有相关样本的列的矩阵?
#3
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.
你可以用其他分布函数代替rnorm,例如runif,来生成其他分布的矩阵。
#4
-2
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!
注意:每个条目都是独立的。所以你不能避免使用for循环,因为你必须为每个独立变量调用rnorm。如果你只调用rnorm(n*m)那是来自同一个随机变量的n*m样本!