Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm using set.seed() but getting different answers in each run [closed]

Tags:

r

I thought if I used set.seed() inside a function then every time I ran that function the same seed would be used and I would get the same quasi random output. Take the following example:

my_fun <- function(n, v1, v2){
  set.seed = 42
  return(runif(n, v1, v2))
}
my_fun(1,2,3)
#> [1] 2.078126
my_fun(1,2,3)
#> [1] 2.918556
my_fun(1,2,3)
#> [1] 2.189768

I was expecting to get the same result every time I ran that function with the same inputs. Can you give me some education on why I don't?

like image 918
JD Long Avatar asked May 08 '18 20:05

JD Long


1 Answers

set.seed() is a function expecting a parameter equal to the value you want to seed the pseudorandom number generator(prng) with. The seed is the value used to start the number generation from. Most prng will use the current time as default, but when you pass it a seed you are determining the starting value and therefore all values to come after it as well.

So you need to call it like set.seed(42) to set your seed appropriately

Here is another question that gives a good response on what this function is actually doing https://stats.stackexchange.com/questions/86285/random-number-set-seedn-in-r

like image 63
James Russo Avatar answered Oct 11 '22 13:10

James Russo