How about this:
library(zoo)
library(tidyverse)
isWoman <- c(rep(FALSE, 40), rep(TRUE, 10)) # the vector to sample from
twoAdjacent <- function(x) rollsum(x, 2) >= 2 # a helper function that calculates for a logical vector whether two TRUEs are next to each other
# and now the simulation (see explanation below)
replicate(
10000
, isWoman %>% sample() %>% twoAdjacent() %>% any() %>% `!`) %>%
mean()
So, important to understand is the %>% (pipe-operator): read it as "then". Read the 3rd line first:
- we take the vector
isWoman
- randomly sort it (
sample())
- see check where there are two adjacent
TRUEs (twoAdjacent())
- check if this appears
anywhere
- and apply a logical NOT (
!)
We replicate this 10000 times, which gives us a logical vector of length 10000. Eventually we pass this (logical) vector to the mean() function where every TRUE is interpreted as a 1 and every FALSE as a 0. Hence, the result is the probability you are looking for.