简体   繁体   English

向 CRAN 提交 package 不接受 function 内的 set.seed 但不知道如何避免它

[英]Submitting a package to CRAN does not accept set.seed inside a function but do not know how to avoid it

I am submitting a package to CRAN, that identifies breaks in a time series, for this in some functions of the package I do Montecarlo simulations.我正在向 CRAN 提交一个 package 以识别时间序列中的中断,为此在 package 的某些功能中,我进行了蒙特卡罗模拟。 In order to guarantee same result for the same input from the functions that perform Montecarlo simulations, I set a seed inside the function.为了保证来自执行蒙特卡罗模拟的函数的相同输入的相同结果,我在 function 中设置了一个种子。 The CRAN moderator tall me: "Please do not set a seed to a specific number within a function." CRAN 版主向我说:“请不要将种子设置为 function 中的特定数字。”

The problem is how to achieve same result with the same input if no seed is set.问题是如果没有设置种子,如何使用相同的输入获得相同的结果。 Here is an example to understand the problem, in which function2 set a seed inside and the result is always equal compare max2 and max4 , instead funtion1 does the same but does not set seed and the result varies.这是一个理解问题的示例,其中function2在里面设置了一个种子,结果总是相等,比较max2max4 ,而funtion1做同样的事情但不设置种子,结果会有所不同。

x <- c(1:100)

#Function without set.seed
function1 <- function(x,simulations = 100){

  mn <- mean(x)
  sd <- sd(x)
  max_vect <- vector(mode = 'double',length = simulations)
  for(i in 1:simulations){
    x_aux <- rnorm(n = length(x),mean = mn,sd = sd)

    max_vect[i] <- max(x_aux)

  }

  return(mean(max_vect))
}

#Function that set.seed
function2 <- function(x,simulations = 100){

  mn <- mean(x)
  sd <- sd(x)
  max_vect <- vector(mode = 'double',length = simulations)
  set.seed(1234)
  for(i in 1:simulations){
    x_aux <- rnorm(n = length(x),mean = mn,sd = sd)

    max_vect[i] <- max(x_aux)

  }

  return(mean(max_vect))
}

max1 <- function1(x)
max2 <- function2(x)

max3 <- function1(x)
max4 <- function2(x)

Agree with comments.同意评论。 Do this做这个

myFunction <-function (x, y,z, seed = NULL) {
if (length(seed) ) set.seed(seed)
# the function guts
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM