Hi,

----- Original Message -----
From: "Serge Boiko" <[EMAIL PROTECTED]>
To: <[EMAIL PROTECTED]>
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
    ans
  }

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

  # Vectorised
  fac3 <- function(n)
     prod(seq(n))

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

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

Cheers,

Kevin

------------------------------------------------
Ko-Kang Kevin Wang
Master of Science (MSc) Student
Department of Statistics
University of Auckland
New Zealand
www.stat.auckland.ac.nz/~kwan022

______________________________________________
[EMAIL PROTECTED] mailing list
http://www.stat.math.ethz.ch/mailman/listinfo/r-help

Reply via email to