I have a vector X of length 1000 containing 10 randomly placed ones and 990 zeros.
I have below function which modifies vector X.
foo <- function(X){
old <- sample(which(X==1),1)
new <- sample(c(1:1000),1)
X[old] <- 0
X[new] <- 1
return(X)
}
Above function does following:
- Locates the ones
- Selects the index of one of them at random
- Selects a random location in X
- Changes the previously located one to a zero
- Changes the random location from step 3 from 0 to 1.
With above code, a 1 can be added to a location which already holds a 1. This I don't want to be possible. In other words, I always want to have 10 ones in my vector.
The solution must be without loops because I am calling this function thousands of times, and speed is of the essence.
Aucun commentaire:
Enregistrer un commentaire