1

I appreciate that sampling from a list of length 1 has little practical use yet all the same I tried the following:

When I run the r snippet sample(c(1,2,3),1) then I obtain a random single value from the list c(1,2,3).

When I run the r snippet sample(c(3),1) then I would expect the number 3 to always be output but I don't, I seem to obtain the same behaviour as above.

Why is this? How can I sample from a list of length 1?

I found that sample(c(3,3),1) does indeed output the intended, but feels not what I had in mind.

Geoff
  • 925
  • 4
  • 14
  • 36

2 Answers2

2

See documentation for 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. 
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • Thanks for that. I had looked at the documentation and it says for x `either a vector of one or more elements from which to choose,`. I didn't get further down! Now I see that what I have is `Note that this convenience feature may lead to undesired behaviour`! – Geoff Nov 13 '20 at 14:25
0

You can use resample() from the gdata package. This saves you having to redefine resample in each new script. Just call

gdata::resample(c(3), 1)

https://www.rdocumentation.org/packages/gdata/versions/2.18.0/topics/resample

trickytank
  • 46
  • 4