mardi 23 mai 2017

R: Sample each element of a vector with specific probability *elegantly*

I wish to sample each element of a vector with specific probability p. This is how I currently do it, I find it hard to believe this is the most elegant way:

vec <- letters[1:5]
p <- 0.8
sampInd <- sample(c(TRUE, FALSE), length(vec), prob = c(p, 1-p), replace = TRUE)
vec[sampInd]
[1] "c" "d" "e"

Another way using a Bernoulli distribution:

sampInd <- ifelse(rbinom(length(vec), 1, p) == 1, TRUE, FALSE)
vec[sampInd]
[1] "a" "b" "c" "e"

Am I missing some base function to do this more elegantly or over complicating my use of sample or rbinom? Don't care much about speed, though it's always a nice thing to have.




Aucun commentaire:

Enregistrer un commentaire