'How to create my own binomial coefficient function in R

I have created a factorial function which is then used to create a function for the binomial coefficient. My factorial function works but the binomial function does not.

I needed to create a factorial function which was then to be used to create a binomial coefficient function using R. I was not allowed to use the base program's functions such as factorial nor choose. I had to use for statements, logics etc. even though it is inefficient.

I had to print the factorial of zero and ten, then the binomial coefficient with n = 5, and k = 2

fact <- function(n) {
  x <- 1 
  if(n == 0) {
    print(1)
  } else {
    for(i in 1:n) { 
      x <- x*i
    }
  }
  print(x)
}

fact(0)
fact(10)

bc <- function(n, k) {
  y <- fact(n) / fact(n - k) * fact(k)
  print(y)
}

bc(5, 2)

For the factorial function I got the correct answer

But for the binomial function I was way off.

If someone can show me where I have made the mistake I would be most appreciative.



Solution 1:[1]

There are quite a few issues here, both relating to basic R coding and coding in general. Let's go through some of them step-by-step:

  1. Your function fact actually does not return anything. All it does at the moment is print values to the console. If you take a look at help("print") it is stated that

    ‘print’ prints its argument and returns it invisibly (via ‘invisible(x)’).

    So in order for fact to actually return a value we can do

    fact <- function(n) {
       x <- 1
       if (n > 0) {
           for (i in 1:n) x <- x * i
       }
       return(x)
    }
    

    I have tidied up your code by removing the unnecessary n == 0 check.

    Note that there is still room for improvement. For example, there are better ways to calculate the factorial of a number. Secondly, your function currently does not properly deal with negative numbers. Generally, the factorial is only defined for non-negative integers. So you can either change fact to return NA for negative numbers, or -- perhaps more interesting -- generalise the factorial function to the Gamma function to allow for any real (or even complex) number. Either way, I'll leave this up to you.

  2. Similarly your function bc also does not return anything, and instead writes the value of y to the console. Furthermore you need to be careful of brackets to make sure that the terms (n - k)! and k! are in the denominator. Both issues can be fixed by writing

    bc <- function(n,k) return(fact(n)/(fact(n - k) * fact(k)))
    
  3. To confirm, we calculate the coefficient for 5 choose 2:

    bc(5, 2)
    #10
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maurits Evers