I wrote this code to check for 3 or more consecutive faces in a simulation of 100000 iterations, with five rolls of a fair die. I think it is in the right track, but I am missing something. I keep getting a missing value error:
nrep = 500000
count = 0
for (i in 1:nrep) {
roll = sample(6, 5)
print(roll)
if (roll[i] == roll[i+1] & roll[i+1] == roll[i+2]) count = count + 1
}
print(count)
Please advise on a correction using base R only.
Adding to my comment, you can use the function rle()
to compute the lengths and values of runs of equal values in a vector. You can do something like the following
nrep = 500000
count = 0
for (i in 1:nrep) {
roll = sample(6, 5, replace = TRUE)
roll_rle = rle(roll)
if (any(roll_rle$lengths >= 3)) {
print(roll)
count = count + 1
}
}