为什么 set.seed() 会影响 R 中的 sample()

编程入门 行业动态 更新时间:2024-10-28 13:18:12
本文介绍了为什么 set.seed() 会影响 R 中的 sample()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

问题

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

这是一个 R 代码:

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

解决方案

根据 ?set.seed

中的帮助文件

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

所以,由于 rnorm 和 sample 都受 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()

本文发布于:2023-11-09 19:16:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573212.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:set   seed   sample

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!