Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R choose() Function - Computing Combinations

R choose() Function - Computing Combinations

R Language Examples R Language Examples

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:

Example

Compute combinations

print

(

choose

(

5

,

2

)

)

   

Choose 2 from 5

print

(

choose

(

10

,

3

)

)

   

Choose 3 from 10

print

(

choose

(

52

,

5

)

)

   

Combinations of 5 playing cards

print

(

choose

(

6

,

0

)

)

   

Choosing 0 has only one way

print

(

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"

)

print

(

choose

(

n, k

)

)

Probability calculation: the number of ways to get exactly 6 heads in 10 coin tosses

print

(

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 R Language Examples