mercredi 19 septembre 2018

Random (?) number generation in R using sample() always returning the same result

I am writing an R script (using RStudio on Ubuntu 18.04), and at a certain point I need to randomly pick (with no replacement) 123 random numbers between 1 and 1040. I do this with:

myvector[sample(1:1040,X,replace=F)] = 1  

where 'myvector' is a 1040-long vector of 0s, and I need to replace 0 with 1 in X=123 random positions.

Every time I copy this exact line of code to the R console and run it, it works as I would expect, picking 123 different numbers at every iteration.

Strangely however, every time I execute the script containing this line of code, it instead picks the same 123 numbers.

At first, I thought this may be due to some trivial object saving/renaming bug, but even if I add

print(sample(1:1040,123,replace=F))

to the script, if picks always the same set of numbers (different from that picked by the code line above, but identical at every iteration).

I haven't invoked set.seed() anywhere within the script and/or ever since I switched the computer on, so I don't understand why it's behaving this way.

Any idea?

Thank you very much




Aucun commentaire:

Enregistrer un commentaire