创建具有最小 运行 长度的二进制值序列

Create sequence of binary values with a minimum run length

我想创建一个特定长度的 0 或 1 的随机序列,比如 100。我唯一的限制是该数字必须至少在两个连续的周期中。

正确序列示例,其中所有运行至少有两个值:

1 1 0 0 0 1 1 1 0 0 0

不正确序列的示例,其中某些运行的值少于两个:

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

这是我的代码,但不起作用:

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)

这是一种使用名为 consecutive_count 的变量的方法,该变量计算在该系列中创建了多少个连续的相同值。

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

这是一个简单的版本。 x 的第一个值设置为随机二项式数(0 或 1)。第二个值必须与第一个相同。然后,如果前两个值相同,则以下代码会检查每次迭代。如果是,则生成随机二项式。如果不是,则 x[i-1] 也被分配为 x[i]

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

这是一个生成任意长度 (n) 的函数版本,同时允许您更改获得 1 超过 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