dimanche 2 juin 2019

R: Using sample when the number of items to choose from can be 1 or greater than one

In R, the sample function picks an element from a list if length is greater than one, or else takes an element from 1 to n if there's only one element (n).

This double behaviour is a problem for me because let's say I have the following code (I've tried to simplify it):

sample(sample(10:20,sample(5,1)),1)

When sample(5,1) is 1, I only get one number, otherwise, I get more than one. And I need to put in a simply way that I want to choose one of the numbers given by sample(10:20,sample(5,1)) (or the only one if there is only one).

Now, I could avoid this with an if:

a<-sample(10:20,sample(5,1))
if(length(a)>1){
  sample(a)
} else {a}

But this gets complicated and there are quite a lot more "samples" that depend on this and it would be very messy.

So I wonder if there's any function or sample argument that chooses the only number that is given if there is only one.

Thank you




Aucun commentaire:

Enregistrer un commentaire