[R] does a factorial function exist

Venables, Bill (CMIS, Cleveland) Bill.Venables at cmis.CSIRO.AU
Thu Jun 24 02:14:08 CEST 1999


Two people now have essentially suggested 

	factorial <- function(n) prod(1:n)

as a possible factorial function.  (One is included below.)  I think it is
important to realise why this is NOT a good suggestion.  In a nutshell: it
is not a vectorized solution.  You may have only scalar arguments in mind
for the factorial function, but other users may not, (and the consensus view
is on their side.)  Also, it doesn't work for n=0 but that's a lesser
issue..

Consider, for example

*	n <- 0:5
*	gamma(n+1)
	[1]    1    1    2    6   24  120
*	prod(1:n)
[1]    0

In writing functions for R or in using the system generally it is important
to make as much use as possible of vectorization for efficiency.  This is
one aspect of what John Chambers calls "taking the `whole object' view" and
is the key to using systems like R effectively.

(Here endeth the sermon).

Bill Venables.

On Wed, 23 Jun 1999, Alex Buerkle wrote:

> 
> I've looked through the documentation with R-0.64.1 and have been unable
> to find a high-level function for evaluation of factorials (i.e., n!, not
> factorial designs).  Is there such a function?

Try 
function(n) {prod(1:n)}

Nicholas

Bill Venables, Statistician, CMIS Environmetrics Project.
Physical address:                            Postal address:
CSIRO Marine Laboratories,                   PO Box 120,       
233 Middle St, Cleveland, Queensland         Cleveland, Qld, 4163
AUSTRALIA                                    AUSTRALIA
Telephone: +61 7 3826 7251
      Fax: +61 7 3826 7304     Email: Bill.Venables at cmis.csiro.au
_______________________________________________________________________



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list