PDF/Tex-file knitr 生成的随机数与控制台中使用相同代码生成的随机数不同
PDF/Tex-file produced by knitr contains different random numbers from those generated with same code in console
Knitr 擅长整合文本和代码输出。使用这个的目标通常被称为'reproducible research'。现在,当这项研究包含随机数(例如多重插补)时,再现性的关键是 R 中的 set.seed
函数。
但不知何故,这两种类型的可重现性不兼容。
查看下面的简短 Rnw 文件。
\documentclass{article}
\begin{document}
When I run the below chunck in the console I get (every time) the following numbers:
$, 94, 96, 92, 99, 57, 44, 45, 35, 43, 44, 71$$
However, when I run the enitre Rnw-program using the 'Compile pdf' button in Rstudio I get (every time) the following numbers:
$, 97, 52, 68, 2, 57, 76, 20, 96, 68, 27, 29$$
What number do \emph{you} get?
<<minimalexample, results = 'markup'>>=
set.seed(20200705)
sample(seq(1, 100), 12, replace = T)
@
\end{document}
我的问题是:
- 这怎么可能?
- 我们可以做些什么来在 运行 代码的两种方式中获得相同的数字吗?
- 当 运行 这个程序 and/or 只有 chunck 时,你 (reader) 得到什么数字?
我成功地在 R 4.0.2 上重现了您的结果。尝试 运行 在您的控制台和 knitr 文件中使用以下行:
RNGkind()
如果我没记错的话,您会看到以下(不同的)输出,具体取决于您运行安装它的位置:
# In the console:
RNGkind()
# [1] "Mersenne-Twister" "Inversion" "Rounding"
# In the knitr file:
RNGkind()
# [1] "Mersenne-Twister" "Inversion" "Rejection"
通读 documentation,您会发现 sample.kind
有所不同。从上面link:
sample.kind
can be "Rounding"
or "Rejection"
, or partial matches to these. The former was the default in versions prior to 3.6.0: it made sample noticeably non-uniform on large populations, and should only be used for reproduction of old results.
您的控制台似乎由于某种原因停留在旧版本的样本生成上。要使用现代 "Rejection"
版本使其 运行,请在您的控制台中执行以下命令:
RNGkind(sample.kind = "Rejection")
然后您应该得到与 knitr 文件中相同的随机序列。
Knitr 擅长整合文本和代码输出。使用这个的目标通常被称为'reproducible research'。现在,当这项研究包含随机数(例如多重插补)时,再现性的关键是 R 中的 set.seed
函数。
但不知何故,这两种类型的可重现性不兼容。
查看下面的简短 Rnw 文件。
\documentclass{article}
\begin{document}
When I run the below chunck in the console I get (every time) the following numbers:
$, 94, 96, 92, 99, 57, 44, 45, 35, 43, 44, 71$$
However, when I run the enitre Rnw-program using the 'Compile pdf' button in Rstudio I get (every time) the following numbers:
$, 97, 52, 68, 2, 57, 76, 20, 96, 68, 27, 29$$
What number do \emph{you} get?
<<minimalexample, results = 'markup'>>=
set.seed(20200705)
sample(seq(1, 100), 12, replace = T)
@
\end{document}
我的问题是:
- 这怎么可能?
- 我们可以做些什么来在 运行 代码的两种方式中获得相同的数字吗?
- 当 运行 这个程序 and/or 只有 chunck 时,你 (reader) 得到什么数字?
我成功地在 R 4.0.2 上重现了您的结果。尝试 运行 在您的控制台和 knitr 文件中使用以下行:
RNGkind()
如果我没记错的话,您会看到以下(不同的)输出,具体取决于您运行安装它的位置:
# In the console:
RNGkind()
# [1] "Mersenne-Twister" "Inversion" "Rounding"
# In the knitr file:
RNGkind()
# [1] "Mersenne-Twister" "Inversion" "Rejection"
通读 documentation,您会发现 sample.kind
有所不同。从上面link:
sample.kind
can be"Rounding"
or"Rejection"
, or partial matches to these. The former was the default in versions prior to 3.6.0: it made sample noticeably non-uniform on large populations, and should only be used for reproduction of old results.
您的控制台似乎由于某种原因停留在旧版本的样本生成上。要使用现代 "Rejection"
版本使其 运行,请在您的控制台中执行以下命令:
RNGkind(sample.kind = "Rejection")
然后您应该得到与 knitr 文件中相同的随机序列。