[R] factorial function

Ko-Kang Kevin Wang Ko-Kang at xtra.co.nz
Fri Feb 14 10:58:03 CET 2003


----- Original Message -----
From: "Serge Boiko" <boiko at demogr.mpg.de>
To: <r-help at stat.math.ethz.ch>
Sent: Friday, February 14, 2003 11:36 PM
Subject: [R] factorial function

> Sorry for the stupid question, but is there the factorial function in
> R? I tried to find it using help.search('factorial') but got nothing
> appropriate.

There isn't.

But there are at least four different ways to do this -- from the S
Programming Workshop (by Dr. Ross Ihaka):

  # Iteration
  fac1 <- function(n) {
    ans <- 1
    for(i in seq(n)) ans <- ans * i

  # Recursion
  fac2 <- function(n)
    if (n <= 0) 1 else n * fac(n - 1)

  # Vectorised
  fac3 <- function(n)

  # Special Mathematical Function -- Gamma
  fac4 <- function(n)

Of these Gamma is probably the most efficient.  Note that the above hasn't
got any debugging codes, you probably want to add them.



Ko-Kang Kevin Wang
Master of Science (MSc) Student
Department of Statistics
University of Auckland
New Zealand

More information about the R-help mailing list