Create sequence of binary values with a minimum run length

Viewed 73

I want to create a random sequence of 0 or 1 of a certain length, say 100. My only restriction is that the number must be at least in two consecutive periods.

Example of correct sequence, where all runs have at least two values:

1 1 0 0 0 1 1 1 0 0 0

Example of incorrect sequence, where some runs have less than two values:

1 0 0 1 0 1 1 1 0 1 1
      ^ ^       ^

This is my code, but is not working:

x <- NULL
x[1] <- sample(c(0, 1), replace = TRUE, size = 1)

for(i in 2:100){
  x[i] <- sample(c(0, 1), replace = TRUE, size = 1)
    
    
  x[i] <- if(x[i] + x[i-1] == 1){ 
            if(x[i-1] == 1){
                1
            } else {
        0
      }
    
  } else {
    sample(c(0, 1), replace = TRUE, size = 1)
  }
}
print(x)
2 Answers

Here is a simple version. The first value of x is set to a random binomial number (0 or 1). The second value must be the same as the first. Then, the following code checks for each iteration if the two previous values are the same. If they are, then a random binomial is generated. If not, then x[i-1] is assigned as x[i] also.

set.seed(1234)
n <- 100
x <- numeric(n)
x[1] <- rbinom(1, 1, .5)
x[2] <- x[1]

for(i in 3:n) {
  if(x[i-1] == x[i-2]) {
    x[i] <- rbinom(1, 1, .5)
  } else {
    x[i] <- x[i-1]
  }
}
x
 [1] 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 1 1 0 0 1 1 0 0 0 1 1 1 1 1 0 0
 [59] 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 0 0 0 0 1 1 0 0 1 1

Here is a function version to generate any length (n), while allowing you to change the probability of getting a 1 over a 0.

my_func <- function(n, prob = 0.5) {
  x <- numeric(n)
  
  x[1] <- rbinom(1, 1, prob)
  x[2] <- x[1]
  
  for(i in 3:n) {
    if(x[i-1] == x[i-2]) {
      x[i] <- rbinom(1, 1, prob)
    } else {
      x[i] <- x[i-1]
    }
  }
  x
}
set.seed(1234)
my_func(n = 10, prob = 0.9)
[1] 1 1 1 1 1 1 1 1 1 1

Here is one way using a variable called consecutive_count which counts how many consecutive same values has been created in the series.

set.seed(1432)
#Initialise the vector of size 100
x <- numeric(100)
#Get the 1st value
x[1] <- sample(c(0,1), 1)
consecutive_count <- 1

for(i in 2:100){
  #If the count is less than 2, repeat the previous value
  if(consecutive_count < 2){
    x[i] <- x[i-1]
    #Increment the counter
    consecutive_count <- consecutive_count + 1
  }  else {
    #Randomly assign 1 or 0
    x[i] <- sample(c(0,1), 1)
    #If the count is same as previous value increment the count
    #Or set consecutive_count to 1.
    if(x[i] == x[i-1]) consecutive_count <- consecutive_count + 1
    else consecutive_count <- 1
  }
}
x

x
#[1] 0 0 0 1 1 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1
#[39] 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 0 0 0 0 1 1
#[77] 1 0 0 0 0 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 0 0
Related