lundi 29 janvier 2018

sample() in R unpredictable when vector length is one

I am trying to debug a short program, and I get a disconcerting result towards the end of sampling from the elements of a vector under some conditions. It happens as the elements of the vector that remain draw down to a single value.

In the specific case I'm referring to the vector is called remaining and contains a single element, the number 2. I would expect that any sampling of size 1 from this vector would stubbornly return 2, since 2 is the only element in the vector, but this is not the case:

Browse[2]> is.vector(remaining)
[1] TRUE
Browse[2]> sample(remaining,1)
[1] 2
Browse[2]> sample(remaining,1)
[1] 2
Browse[2]> sample(remaining,1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 2
Browse[2]> sample(x=remaining, size=1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 1
Browse[2]> sample(x=remaining, size=1)
[1] 1

As you can see, sometimes the return is 1 and some others, 2.

What am I misunderstanding about the function sample()?




Aucun commentaire:

Enregistrer un commentaire