Search code examples
rmontecarlocranrandom-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. In order to guarantee same result for the same input from the functions that perform Montecarlo simulations, I set a seed inside the function. The CRAN moderator tall me: "Please do not set a seed to a specific number within a 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.

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)


Solution

  • Agree with comments. Do this

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