2

sample(x,n) The parameters are the vector, and how many times you wish to sample

sample(c(5,9),1) returns either 5 or 9

however,

sample(5,1) returns 1,2,3,4, or 5?

I've read the help section:

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). See the examples.

But is there a way to make it not do this? Or do I just need to include an if statement to avoid this.

Shree
  • 10,835
  • 1
  • 14
  • 36
sahimat
  • 145
  • 1
  • 5

2 Answers2

3

Or do I just need to include an if statement to avoid this.

Yeah, unfortunately. Something like this:

result = if(length(x) == 1) {x} else {sample(x, ...)}
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
2

Here's an alternative approach: you simply subset a random value from your vector like this -

set.seed(4)

x <- c(5,9)
x[sample(length(x), 1)]
[1] 9

x <- 5
x[sample(length(x), 1)]
[1] 5
Shree
  • 10,835
  • 1
  • 14
  • 36