Skip to main content
v2026.11,858 entries · CC-BY 4.0

Factorials in R: factorial(), gamma(x+1), prod() and cumprod()

How to calculate factorials in R with factorial(), gamma(x+1), prod() and cumprod(), plus the NaN and zero cases, all checked against the R manual.

Written and maintained by CASRAI Editorial Board

Last updated

Factorials in R are computed with the base function factorial(x), which the R reference manual defines as gamma(x+1). For whole numbers that equals x!, so factorial(5) returns 120. Because it is defined through the gamma function, the same call also covers non-integers and explains why negative integers return NaN. This guide covers the function, its vectorised and log-scale companions, and the base R routes that give the same answer: prod(), cumprod() and a plain loop.

What it is used for in research

A factorial counts the ways to order n distinct items (n! = n × (n−1) × … × 1, with 0! = 1). Researchers meet it when counting permutations of group labels, as in permutation tests, when building binomial coefficients, and in count-data formulas such as the Poisson distribution, whose probability mass function contains k!. It also appears when working out how many ways a sample can be drawn or ordered, as in sampling with replacement.

One disambiguation: the “factorial” in a factorial experiment is a different idea (crossing several factors in a design). For that, see factorial designs and running ANOVA in R. The rest of this page is about the factorial function x!.

Install or access

Nothing needs installing beyond R itself. factorial(), lfactorial(), gamma(), choose(), prod() and cumprod() all belong to the base package, which R loads at start-up, so no library() call is required. R is distributed free from the R Project (r-project.org); the function documentation is the R reference manual page “Special Functions of Mathematics”.

Step-by-step: calculating a factorial in R

1. Factorial of one number (factorial function in R)

  1. Open an R console or script.
  2. Type factorial(5) and run it. The result is 120, because 5 × 4 × 3 × 2 × 1 = 120.
  3. Check zero: factorial(0) returns 1, since gamma(1) = 1 and 0! is defined as 1.

2. Factorials of many numbers at once

The manual states that the argument is a numeric vector, so one call handles a whole sequence: factorial(0:10) returns 0! through 10!, ending in 3628800 for 10!.

3. A factorial program in R with a loop

If you want to see the arithmetic, a loop reproduces the same product:

n <- 5
result <- 1
for (i in seq_len(n)) {
  result <- result * i
}
result   # 120

For n = 0, seq_len(0) is empty, the loop never runs and result stays 1, which is the correct value of 0!.

4. Without a loop: prod() and cumprod()

prod(1:5) multiplies the vector 1, 2, 3, 4, 5 and returns 120. The prod manual page itself pairs prod(1:7) with gamma(8) as equivalent. To get every factorial up to n in one pass, use cumprod(1:n), which keeps the running product: cumprod(1:5) gives 1, 2, 6, 24, 120, that is 1! to 5!. The manual’s own example is cumprod(1:10).

Take care with zero: prod(1:0) multiplies the vector c(1, 0) and returns 0, not 1. Use prod(seq_len(0)), because the manual defines the product of an empty set as one.

5. Large values on the log scale

lfactorial(x) is defined as lgamma(x+1), the natural log of x!. Use it when you only need the logarithm, for example when summing log-probabilities, so you never have to form a very large product. The manual’s examples include factorial(100) and lfactorial(10000).

Output and how to read it

  • Whole numbers: factorial(n) is n!, returned as a numeric value.
  • Non-integers: because factorial(x) is gamma(x+1), factorial(0.5) is gamma(1.5), which mathematically is √π ÷ 2 (about 0.886). It is the gamma function evaluated at x+1, not a counting result.
  • Negative integers: the manual says the gamma function “is not defined for zero and negative integers (when NaN is returned)”. Since factorial(-1) is gamma(0), expect NaN.
  • cumprod output: for integer input cumprod returns a numeric vector, and an NA in the input propagates to every later element.

Worked link to combinations: choose(5, 2) returns 10, which equals 5! ÷ (2! × 3!) = 120 ÷ 12. The manual lists choose(n, k) next to factorial() in the same family of functions, and a non-integer k is rounded to an integer with a warning.

Troubleshooting

  • NaN returned: the input is a negative integer, where gamma is undefined. Check the sign of the value you passed.
  • Unexpected decimal result: a non-integer was passed, so you got the gamma-based value. Round with round(x) first if you meant a count.
  • Result of 1 or 0 when you expected a count: check whether you used prod(1:0) (gives 0) instead of prod(seq_len(0)) (gives 1).
  • Very large arguments: if you only need ratios or log-probabilities, work on the log scale with lfactorial() or lchoose() instead of forming the full factorial; the manual’s own example is lfactorial(10000).
  • Everything after an NA is NA: this is documented cumprod behaviour; remove or fix the missing value first.

Other base R routes that give the same answer

All of these are free and part of base R; each row comes from the R reference manual pages cited below.

Goal Base R call What the manual says
x! for one value or a vector factorial(x) Defined as gamma(x+1)
Same thing through gamma gamma(x+1) Undefined (NaN) for zero and negative integers
Natural log of x! lfactorial(x) Defined as lgamma(x+1)
Product of 1 to n prod(1:n) Returns a length-one double; example prod(1:7) matches gamma(8)
All factorials 1! to n! cumprod(1:n) Cumulative products; NA propagates to later elements
Number of combinations choose(n, k) Listed with factorial in the special-functions page

For resampling designs that rely on these counts, see bootstrapping in statistics.

FAQ

How do I write a factorial function in R?

You do not need to: factorial() is built in. To write your own as an exercise, multiply 1 through n in a loop, as in step 3, or use prod(seq_len(n)).

Is a loop different from the built-in factorial in R programming?

None in the result for whole numbers. The built-in is vectorised and defined through gamma(x+1); a loop is only useful for seeing the arithmetic.

How do I get 0! in R?

factorial(0) returns 1. If building it from a product, use prod(seq_len(0)), which is 1 because an empty product is one.

How do I get all factorials from 1 to n?

Use cumprod(1:n) or factorial(1:n).

Why does factorial(-1) return NaN?

Because it equals gamma(0), and the gamma function is not defined for zero and negative integers.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Factorials in R: factorial(), gamma(x+1), prod() and cumprod()

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.