在R中本地(非全局)设置种子 [英] setting seed locally (not globally) in R

查看:133
本文介绍了在R中本地(非全局)设置种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想仅在本地(内部函数)中设置R的种子,但似乎R不仅在本地设置种子,而且在全局设置种子.这是我正在尝试(而不是尝试)做的一个简单示例.

I'd like to set seeds in R only locally (inside functions), but it seems that R sets seeds not only locally, but also globally. Here's a simple example of what I'm trying (not) to do.

myfunction <- function () {
  set.seed(2)
}

# now, whenever I run the two commands below I'll get the same answer
myfunction()
runif(1)

所以,我的问题是:为什么R全局设置种子而不是仅在函数内部设置种子?以及如何让R仅在函数内部设置种子?

So, my questions are: why does R set the seed globally and not only inside my function? And how I can make R to set the seed only inside my function?

推荐答案

像这样的事情对我有用:

Something like this does it for me:

myfunction <- function () {
  old <- .Random.seed
  set.seed(2)
  res <- runif(1)
  .Random.seed <<- old
  res
}

或更优雅:

myfunction <- function () {
  old <- .Random.seed
  on.exit( { .Random.seed <<- old } )
  set.seed(2)
  runif(1)
}

例如:

> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.3472722
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.4887732

这篇关于在R中本地(非全局)设置种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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