首页 > 解决方案 > R 随机数生成器的版本会影响 edx Statistics 和 R 课程答案的正确性

问题描述

很抱歉在这里问这个问题,但网站上没有这门课程的讨论页面,它提到了 stackoverflow 来提出任何问题。这是来自这个 edx 课程

Q1:使用以下数据集:

'''
url <- "https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extdata/babies.txt"
filename <- basename(url)
download(url, destfile=filename)
babies <- read.table("babies.txt", header=TRUE)
'''

分为两组(不吸烟和吸烟):

bwt.nonsmoke <- filter(babies, smoke==0) %>% select(bwt) %>% unlist 
bwt.smoke <- filter(babies, smoke==1) %>% select(bwt) %>% unlist

将种子设置为 1,并从大小为 N=25 的非吸烟母亲 (dat.ns) 中获取样本。然后,在不重新设置种子的情况下,从吸烟的母亲(dat.s)那里采集相同大小的样本。计算 t 统计量(称为 tval)。

t 统计量的绝对值是多少?

我是这样做的:

set.seed(1)
dat.ns <- sample(bwt.nonsmoke,25)
dat.s <- sample(bwt.smoke,25)
tval <- t.test(dat.ns,dat.s)$statistic
tval

这给出了显然是错误的值 2.120904。我还尝试在每个样本之前将种子设置为 1,如下所示:

set.seed(1)
dat.ns <- sample(bwt.nonsmoke,25)
set.seed(1)
dat.s <- sample(bwt.smoke,25)
tval <- t.test(dat.ns,dat.s)$statistic
tval

这给出了 1.573627 的 t 值,这也是错误的。我不确定我做错了什么,我需要一些帮助。

标签: rrandomstatisticsedx

解决方案


R 中的随机数生成器在 R 版本 3.6.0 中发生了显着变化,正如 R Bloggers 文章R 3.6.0 中的新功能中所强调的那样

如果您使用的是 3.6.0 之前的 R 版本,您将根据您的代码获得以下 t 检验统计信息:

> RNGversion("3.5.3")
Warning message:
In RNGkind("Mersenne-Twister", "Inversion", "Rounding") :
  non-uniform 'Rounding' sampler used
> set.seed(1)
> dat.ns <- sample(bwt.nonsmoke,25)
> dat.s <- sample(bwt.smoke,25)
> t.test(dat.ns,dat.s)

    Welch Two Sample t-test

data:  dat.ns and dat.s
t = 2.1209, df = 47.693, p-value = 0.03916
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
  0.5141953 19.3258047
sample estimates:
mean of x mean of y 
   124.68    114.76 

如果您使用 R 3.6.0 或更高版本,您将使用相同的代码获得以下答案。

> # redo with RNVversion(3.6.3)
> RNGversion("3.6.3")
> set.seed(1)
> dat.ns <- sample(bwt.nonsmoke,25)
> dat.s <- sample(bwt.smoke,25)
> t.test(dat.ns,dat.s)

    Welch Two Sample t-test

data:  dat.ns and dat.s
t = 1.6593, df = 47.58, p-value = 0.1036
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -1.79772 18.75772
sample estimates:
mean of x mean of y 
   125.12    116.64 

底线:检查用于创建测验答案的 R 版本以确认随机数生成器的版本。


推荐阅读