Related questions: one, two.
nCr <- function(n, r) {
if (r == 0 | r == n) return (1)
else return (nCr(n-1, r-1) + nCr(n-1, r))
}
nCr(20, 6)
[1] 38760
choose(20, 6)
[1] 38760
Note the performance of the built-in function.
system.time(for(i in 1:10) nCr(20, 6))
## user system elapsed
## 8.74 0.00 8.90
system.time(for(i in 1:10) choose(20, 6))
## user system elapsed
## 0 0 0
The performance problems partly occur because the function is called with the same inputs many time. You can make nCr
faster by caching the results ‐ this technique is useful for many recursive functions, though notice that the built-in function is still much faster.
library(memoise)
nCr2 <- memoise(nCr)
system.time(for(i in 1:10) nCr2(20, 6))
## user system elapsed
## 0.88 0.00 0.91