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)