R choose() Function - Computing Combinations
The R choose() function is used to compute the number of combinations C(n, k) of choosing k elements from n elements.
Combinations are a fundamental concept in probability and statistics, also known as binomial coefficients.
The syntax of the choose() function is as follows:
choose(n, k)
Parameter Description:
-
n The total number of elements (integer).
-
k The number of elements to choose (integer), which must satisfy 0 <= k <= n。
Example
Compute combinations
(
choose
(
5
,
2
)
)
Choose 2 from 5
(
choose
(
10
,
3
)
)
Choose 3 from 10
(
choose
(
52
,
5
)
)
Combinations of 5 playing cards
(
choose
(
6
,
0
)
)
Choosing 0 has only one way
(
choose
(
6
,
6
)
)
Choosing all also has only one way
The output of the code above is:
[1] 10
[1] 120
[1] 2598960
[1] 1
[1] 1
choose() can also take vectors to compute multiple combinations:
Example
The 5th row of the binomial coefficient triangle (Pascal's triangle)
n
<-
5
k
<-
0
:
n
cat
(
"C(5, k) k = 0 to 5:\n"
)
(
choose
(
n, k
)
)
Probability calculation: the number of ways to get exactly 6 heads in 10 coin tosses
(
paste
(
"The number of ways to get exactly 6 heads in 10 tosses is"
,
choose
(
10
,
6
)
,
"ways"
)
)
The output of the code above is:
C(5, k) k = 0 到 5:
[1] 1 5 10 10 5 1
[1] "10 次掷硬币中恰好 6 次正面的方式有 210 种"
R Language Examples