-2

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)
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
rnorouzian
  • 7,397
  • 5
  • 27
  • 72

2 Answers2

1

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.

jeremycg
  • 24,657
  • 5
  • 63
  • 74
0
gen <- function(n)  {replicate(1000,sample(1:n,1))}
Mouad_Seridi
  • 2,666
  • 15
  • 27