I want to remove n elements chosen randomly from a vector, where n is greater than or equal to 0.
n is sampled from a binomial, and small, possibly 0.
I want to do this as efficiently as possible, so the code can be run many times. The issue is that using vec[-sample(vec,n)] may give a null vector, if n = 0.
I had a couple of ideas, I was wondering if anyone knows of a nicer or faster way to get around the problem.
- Using a minus sign, and an if function before.
# y is a vector of length 10000
n <- rbinom(n = 1, size = 10000, p = 0.0001)
if (length(n) != 0){
y <- y[-sample((1:10000), size = n)]
}
- Selecting all other elements.
# y is a vector of length 10000
n <- rbinom(n = 1, size = 10000, p = 0.0001)
n <- 10000 - n
y <- sample(y, size = n)