Calculate a probability - Monte Carlo (reprex)

# The variable `B` specifies the number of times we want the simulation to run. Let's run the Monte Carlo simulation 10,000 times.
B <- 10000

# Use the `set.seed` function to make sure your answer matches the expected result after random sampling.
set.seed(1)

# Create an object called `results` that replicates the sample code for `B` iterations and tallies the number of simulated series that contain at least four wins for the Cavs.
results <- replicate(B, {simulated_series <- sample(c(0,1), 6, replace = TRUE, prob = c(0.5, 0.5)); 
sum(simulated_series >= 4)})  


# Calculate the frequency out of `B` iterations that the Cavs won at least four games in the remainder of the series. Print your answer to the console.
mean(results)

The original code is:

n <- 6
l <- list(0:1) 
possibilities <- data.frame(expand.grid(rep(l, n)))   
results <- rowSums(possibilities)=>4       
mean(results)

I'm trying to convert it to a monte carlo simulation but it's not working

Hi there, and welcome to community.rstudio.com! It sounds like this might be a homework question. If it is, please see our homework policy.

4 Likes

The problem is that you are sampling from the two values 0 and 1, six times, and then want to know the proportion of trials with a value equal or higher than 4. That's why you get zero. I don't know what are you aiming, but I can imagine you want to sum the values, so, if you do it:

results <- replicate(B, {simulated_series <- sum(sample(c(0,1), 6, replace = TRUE, prob = c(0.5, 0.5))); 
sum(simulated_series >= 4)})  

then with the mean you get a probability value

mean(results)
[1] 0.3412

That matches the original code output

cheers
Fer