繁体   English   中英

从 dplyr 中均匀分布的随机样本生成的相同值

[英]Identical values generated from random samples from a uniform distribution in dplyr

这是对上一个问题的跟进。 我的问题没有完全制定,因此在我的上一篇文章中没有完全回答。 原谅我,我是使用堆栈溢出的新手。

我的教授布置了一个问题集,要求我们使用 dplyr 和其他 tidyverse 包。 我非常清楚,我尝试执行的大多数(如果不是全部)任务都可以在基础 r 中执行,但这与我的指示不一致。

首先,我们被要求从均匀分布中生成 1000 个随机样本的 tibble:

2a.  Create a new tibble called uniformDf containing a variable called unifSamples that contains 10000 random samples from a uniform distribution.  You should use the runif() function to create the uniform samples. {r 2a}

uniformDf <- tibble(unifSamples = runif(1000))

这很顺利。

然后我们被要求在这个 tibble 中循环 1000 次,每次选择 20 个随机样本并计算平均值并将其保存到一个 tibble 中:

2c.  Now let's loop through 1000 times, sampling 20 values from a uniform distribution and computing the mean of the sample, saving this mean to a variable called sampMean within a tibble called uniformSampleMeans. {r 2c}

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

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

# 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] <- uniformDf %>%
  sample_n(unif_sample_size) %>%
  summarize(sampMean = mean(sampMean))
}

这一切都在运行,好吧,我相信直到我看到我的uniformSampleMeans 看起来像这样:

1   0.471271611726843
2   0.471271611726843
3   0.471271611726843
4   0.471271611726843
5   0.471271611726843
6   0.471271611726843
7   0.471271611726843
...
1000    0.471271611726843

所有值都相同! 有没有人知道为什么我的输出是这样的? 如果它们以 +/- 0.000 倍的值变化,我就不那么担心了,因为这是从 0 到 1 的分布,但这些值甚至到小数点后 15 位都相同! 任何帮助深表感谢!

以下选择随机unif_sample_size行并给出它的mean

library(dplyr)
uniformDf %>% sample_n(unif_sample_size) %>% pull(unifSamples) %>% mean
#[1] 0.5563638

如果您想这样做n次,请使用replicate并重复n

n <- 10
replicate(n, uniformDf %>%
               sample_n(unif_sample_size) %>%
               pull(unifSamples) %>% mean)
#[1] 0.5070833 0.5259541 0.5617969 0.4695862 0.5030998 0.5745950 0.4688153 0.4914363 0.4449804 0.5202964

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM