dogmom
dogmom

Reputation: 31

Calculate factorial of each value in a vector

I am stuck trying to write a function that will calculate n! for each element of a vector without using if/then statements, the factorial function, or a loop. I know cumprod can be used for this but can't get it to work.

#Code
x <- c(5, 2, 3, 8, 8, 1, 1, 7)
(y <-cumprod(x[i:1]))

Upvotes: 3

Views: 550

Answers (2)

Sotos
Sotos

Reputation: 51622

A way to avoid factorial and use cumprod is to loop over x and do the cumprod of the sequence of each value, i.e.

sapply(x, function(i) tail(cumprod(seq(i)), 1))
#[1]   120     2     6 40320 40320     1     1  5040

A couple of more options can be:

sapply(x, function(i) Reduce(`*`, seq(i)))

And as @jogo comments,

sapply(x, function(i) prod(seq(i)))

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102920

Try factorial

> factorial(x)
[1]   120     2     6 40320 40320     1     1  5040

or gamma

> gamma(x+1)
[1]   120     2     6 40320 40320     1     1  5040

or mapply + prod

> mapply(function(a,b) prod(a:b),1,x)
[1]   120     2     6 40320 40320     1     1  5040

Upvotes: 1

Related Questions