[R] factorial function
Ko-Kang Kevin Wang
Ko-Kang at xtra.co.nz
Fri Feb 14 10:58:03 CET 2003
Hi,
----- 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
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
More information about the R-help
mailing list