为什么 set.seed() 会影响 R 中的 sample() [英] Why set.seed() affects sample() in R

查看:45
本文介绍了为什么 set.seed() 会影响 R 中的 sample()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为 set.seed() 只会让随机变量生成器(例如,rnorm)为任何特定的输入值集生成唯一的序列.>

然而,我想知道,为什么当我们设置 set.seed() 时,函数 sample() 不能正确地完成它的工作?

问题

具体来说,给定下面的例子,有没有一种方法可以在 rnorm 之前使用 set.seedsample<如果多次运行 sample,/code> 仍会从此 rnorm 生成新的随机样本?

这是一个 R 代码:

set.seed(123458)x.y = 范数(1e2)采样 = 样本(x = x.y,大小 = 20,替换 = TRUE)绘图(采样)

解决方案

根据 ?set.seed

中的帮助文件<块引用>

"如果用seed = NULL调用它会重新初始化(见注意"),好像没有种子尚未设置."

所以,由于 rnormsample 都受 set.seed() 的影响,你可以这样做:

set.seed(639245)rn <- norm(1e2)set.seed(NULL)样本(rn,5)

I always thought set.seed() only makes random variable generators (e.g., rnorm) to generate a unique sequence for any specific set of input values.

However, I'm wondering, why when we set the set.seed(), then the function sample() doesn't do its job correctly?

Question

Specifically, given the below example, is there a way I can use set.seed before the rnorm but sample would still produce new random samples from this rnorm if sample is run multiple times?

Here is an R code:

set.seed(123458)
x.y = rnorm(1e2)

sampled = sample(x = x.y, size = 20, replace = TRUE)

plot(sampled)

解决方案

As per the help file at ?set.seed

"If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set."

So, since rnorm and sample are both affected by set.seed(), you can do:

set.seed(639245)
rn <- rnorm(1e2)
set.seed(NULL)
sample(rn,5)

这篇关于为什么 set.seed() 会影响 R 中的 sample()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆