R choose() function - calculate combinations
The R choose() function is used to calculate the number of combinations of choosing k elements from n elements, C(n, k).
The combination number is a fundamental concept in probability theory and statistics, also known as the binomial coefficient.
The syntax of the choose() function is as follows:
choose(n, k)
Parameter description:
nTotal number of elements (integer).
kNumber of elements to select (integer), must satisfy 0 <= k <= n.
Examples
# Calculate combinations
print(choose(5, 2)) # Choose 2 from 5
print(choose(10, 3)) # Choose 3 from 10
print(choose(52, 5)) # Number of 5-card poker combinations
print(choose(6, 0)) # Choosing 0, there is only one way
print(choose(6, 6)) # Choosing all, also only one way
print(choose(5, 2)) # Choose 2 from 5
print(choose(10, 3)) # Choose 3 from 10
print(choose(52, 5)) # Number of 5-card poker combinations
print(choose(6, 0)) # Choosing 0, there is only one way
print(choose(6, 6)) # Choosing all, also only one way
Executing the above code outputs:
[1] 10 [1] 120 [1] 2598960 [1] 1 [1] 1
choose() can also accept vectors to calculate multiple combinations:
Examples
# Row 5 of the binomial coefficient triangle (Pascal's triangle)
n <- 5
k <- 0:n
cat("C(5, k) k = 0 to 5:\n")
print(choose(n, k))
# Probability calculation: number of combinations of exactly 6 heads when tossing a coin 10 times
print(paste("Number of ways to get exactly 6 heads in 10 coin tosses:",
choose(10, 6), "ways"))
n <- 5
k <- 0:n
cat("C(5, k) k = 0 to 5:\n")
print(choose(n, k))
# Probability calculation: number of combinations of exactly 6 heads when tossing a coin 10 times
print(paste("Number of ways to get exactly 6 heads in 10 coin tosses:",
choose(10, 6), "ways"))
Executing the above code outputs:
C(5, k) k = 0 到 5: [1] 1 5 10 10 5 1 [1] "10 次掷硬币中恰好 6 次正面的方式有 210 种"Other Extensions
R Language Examples