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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With