使用for循环从正态分布中抽样

问题描述 投票:0回答:1

因此,我每次尝试从正态分布中采样1000次,然后根据该正态分布计算20个随机样本的平均值。


unif_sample_size = 20 # sample size
n_samples = 1000 # number of samples

# set up q data frame to contain the results
uniformSampleMeans <- tibble(sampMean = runif(n_samples, unif_sample_size))


# loop through all samples.  for each one, take a new random sample, 
# compute the mean, and store it in the data frame

for (i in 1:n_samples){
  uniformSampleMeans$sampMean[i] = summarize(uniformSampleMeans = mean(unif_sample_size))
}

我成功生成了小标题,但是值是“ NaN”。另外,当我进入for循环时,我得到一个错误。

Error in summarise_(.data, .dots = compat_as_lazy_dots(...)) : argument ".data" is missing, with no default

任何见识将不胜感激!

r loops dplyr normal-distribution
1个回答
0
投票

您不需要dplyr。

rep<-1000
size<-20

# initialize the dataframe
res<-data.frame(rep=NA,mean=NA)

for ( i in 1:rep) {
        samp<-rnorm(size) # here you actually create your sample of 20 numbers from the normal distribution
        res[i,]$rep<-i #save in the first column the number of the replicate sampling (optional)
        res[i,]$mean<-mean(samp) # here you calculate the mean of the random sample and store it into the datafra
}
res
© www.soinside.com 2019 - 2024. All rights reserved.