Saturday, January 31, 2015

R1. The choose function in R

The choose function finds out how many combinations we have of k elements, from a total of n elements.


For example for {1,2,3}, we have 3 combinations {1,2},{1,3},{2,3}


For combinations, we have to remember order is not important.

# ex1a.R
a <- choose(k=2,n=3)
b <- choose(3,2)
c <- choose(2,n=3)
print(a)
print(b)
print(c)

We may write a function using the factorial definition

# ex1b.R
choose1 <- function(n,k) {
  factorial(n)/factorial(k)/factorial(n-k)
}
a <- choose1(k=2,n=3)
b <- choose1(3,2)
c <- choose1(2,n=3)
print(a)
print(b)
print(c)

No comments:

Post a Comment