📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Calculating a Probability

Extended Example

Suppose we have n independent events, and the ith event has the probability pi of occurring. What is the probability of exactly one of these events occurring?

Suppose first that n = 3 and our events are named A, B, and C. Then we break down the computation as follows:

P(exactly one event occurs) =

P(A and not B and not C) +
P(not A and B and not C) +
P(not A and not B and C)

In the above, P(A and not B and not C) would be pA × (1 − pB) × (1 − pC), and so on.

For n events the same idea gives: for each event i, multiply pi by (1 − pj) for every other event j, and add up these n results.

Example:

Here is the code to compute this, with our probabilities pi contained in the vector p. In the code, p[-i] means "all the elements of p except the ith", so prod(1 - p[-i]) is the probability that none of the other events occurs.

# function to calculate the probability that exactly one event occurs
exactlyone <- function(p) {
  n <- length(p)
  total <- 0

  # Iterate through all event probabilities
  for (i in 1:n) {
    prob_one <- p[i] * prod(1 - p[-i])
    total <- total + prob_one
  }

  return(total)
}

Sample Run 1

# Calling the function
> p <- c(0.2, 0.5, 0.3)
> event_pr <- exactlyone(p)
> cat("The Probability that exactly one event occurs:", event_pr)

Output:

The Probability that exactly one event occurs: 0.47

Sample Run 2

# Calling the function
> p <- c(0.3, 0.5, 0.7)
> event_pr <- exactlyone(p)
> cat("The Probability that exactly one event occurs:", event_pr)

Output:

The Probability that exactly one event occurs: 0.395