lundi 23 mai 2016

Select random index in vector which meets requirements

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:

  1. Locates the ones
  2. Selects the index of one of them at random
  3. Selects a random location in X
  4. Changes the previously located one to a zero
  5. 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