How to generate random integers in R so that no tw

2019-06-08 03:00发布

问题:

Is there a method to generate random integers in R such that any two consecutive numbers are different? It is probably along the lines of x[k+1] != x[k] but I can't work out how to put it all together.

回答1:

Not sure if there is a function available for that. Maybe this function can do what you want:

# n = number of elements
# sample_from = draw random numbers from this range
random_non_consecutive <- function(n=10,sample_from = seq(1,5))
{
  y=c()
  while(length(y)!=n)
  {
    y= c(y,sample(sample_from,n-length(y),replace=T))
    y=y[!c(FALSE, diff(y) == 0)]
  }
  return(y)
}

Example:

random_non_consecutive(20,c(2,4,6,8))
[1] 6 4 6 2 6 4 2 8 4 2 6 2 8 2 8 2 8 4 8 6

Hope this helps.


The function above has a long worst-case runtime. We can keep that worst-case more constant with for example the following implementation:

# n = number of elements
# sample_from = draw random numbers from this range
random_non_consecutive <- function(n=10,sample_from = seq(1,5))
{
  y= rep(NA, n)
  prev=-1 # change this if -1 is in your range, to e.g. max(sample_from)+1
  for(i in seq(n)){
    y[i]=sample(setdiff(sample_from,prev),1)
    prev = y[i]
  }
  return(y)
}


回答2:

Another approach is to over-sample and remove the disqualifying ones as follows:

# assumptions
n <- 5               # population size
sample_size <- 1000


# answer
mu <- sample_size * 1/n
vr <- sample_size * 1/n * (1 - 1/n)
addl_draws <- round(mu + vr, 0)


index <- seq(1:n)
sample_index <- sample(index, sample_size + addl_draws, replace = TRUE)


qualified_sample_index <- sample_index[which(diff(sample_index) != 0)]
qualified_sample_index <- qualified_sample_index[1:sample_size]

# In the very unlikely event the number of qualified samples < sample size,
# NA's will fill the vector.  This will print those N/A's
print(which(is.na(qualified_sample_index) == TRUE))