0

I do not understand how the sample function is working if I have a vector as argument with only one element to sample from (and I just want to sample one element).

I am doing a simulation and me input vector x is going to be of different size every time my loop runs one step. But when the vector is containing only one element, for example x = c(3), it should be sample 3, but I doesn't it starts to sample 2 and 1 all kind of numbers. I have tried to use set.seed and changed the replace argument, but something is wrong. Does anyone know what's going on here?

enter image description here

ZygD
  • 22,092
  • 39
  • 79
  • 102
  • 2
    Please induce a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of your data rather than an image. – user438383 Apr 05 '21 at 13:36

1 Answers1

0

From ?sample:

If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as sample(x).

So this behavior is expected if undesirable. A possible solution is in the answer linked by user20650.

Dan Adams
  • 4,971
  • 9
  • 28