# Step 1: Generate all possible outcomes of rolling a die three times
# The expand.grid function creates a data frame from all combinations of the provided vectors.
# Here, we are simulating the roll of a six-sided die three times.
outcomes <- expand.grid(1:6, 1:6, 1:6)
nrow(outcomes)
## [1] 216
# Step 2: Calculate the sum for each set of outcomes
# The rowSums function calculates the sum of values in each row of the data frame.
# Each row represents a unique set of outcomes from rolling the die three times,
# and rowSums provides the total sum for each set.
sums <- rowSums(outcomes)
sums
##   [1]  3  4  5  6  7  8  4  5  6  7  8  9  5  6  7  8  9 10  6  7  8  9 10 11  7
##  [26]  8  9 10 11 12  8  9 10 11 12 13  4  5  6  7  8  9  5  6  7  8  9 10  6  7
##  [51]  8  9 10 11  7  8  9 10 11 12  8  9 10 11 12 13  9 10 11 12 13 14  5  6  7
##  [76]  8  9 10  6  7  8  9 10 11  7  8  9 10 11 12  8  9 10 11 12 13  9 10 11 12
## [101] 13 14 10 11 12 13 14 15  6  7  8  9 10 11  7  8  9 10 11 12  8  9 10 11 12
## [126] 13  9 10 11 12 13 14 10 11 12 13 14 15 11 12 13 14 15 16  7  8  9 10 11 12
## [151]  8  9 10 11 12 13  9 10 11 12 13 14 10 11 12 13 14 15 11 12 13 14 15 16 12
## [176] 13 14 15 16 17  8  9 10 11 12 13  9 10 11 12 13 14 10 11 12 13 14 15 11 12
## [201] 13 14 15 16 12 13 14 15 16 17 13 14 15 16 17 18
# Step 3: Count the outcomes where the sum is greater than 9
# The sum function here is used to count the number of true instances in the logical vector (sums > 9).
# This logical vector has TRUE values where the condition (sum > 9) is met and FALSE otherwise.
# Summing this vector gives the count of TRUE instances, which is the count of outcomes where the sum is greater than 9.
count_greater_than_9 <- sum(sums > 9)
count_greater_than_9
## [1] 135
# Step 4: Calculate the probability
# The probability is calculated by dividing the count of outcomes where the sum is greater than 9
# by the total number of possible outcomes.
# nrow(outcomes) gives the total number of rows in the outcomes data frame, which represents all possible outcomes.
probability_greater_than_9 <- count_greater_than_9 / nrow(outcomes)

# Step 5: Print the probability
probability_greater_than_9
## [1] 0.625