Search code examples
rfunctionrandomsampling

Can `sample()` in R just sample in a specified order?


I was wondering how I could generate 1000 integers from 1 to 1000, one at a time in R. Making this a function, this means on the first run of the function, the function should produce 1, the second run 2, on the third run 3, ... 1000?

I have tried the following in R with no success:

gen = function(n){
  sample(1:n, 1, replace = FALSE)
  }
gen(1000)

Solution

  • This is pretty bad practice, and you would be better rethinking your plan, but we can do it using a global variable, using <<-:

    myfunc <- function(){
      if(!exists('mycounter')){
        mycounter<<-1
      }else {
        mycounter <<- mycounter + 1
      }
      return(mycounter)
    }
    
    > myfunc()
    [1] 1
    > myfunc()
    [1] 2
    > myfunc()
    [1] 3
    > myfunc()
    [1] 4
    

    You could extend this to eg: index another vector of randoms. Though, set.seed() would probably be want you want.