Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R prod() Function - Computing Products

R prod() Function - Computing Products

R Language Examples R Language Examples

The R prod() function is used to compute the product of all elements in a vector.

prod() is often used when calculating geometric means, factorials, or combinatorial probabilities.

The syntax of the prod() function is as follows:

prod(x, na.rm = FALSE)

Parameter Description:

Example

Create a vector

x

<-

c

(

1

,

2

,

3

,

4

,

5

)

Compute the product (equivalent to 5!)

result.

prod

<-

prod

(

x

)

print

(

result.

prod

)

Verification: compare with factorial(5)

print

(

factorial

(

5

)

)

The output of the code above is:

[1] 120

[1] 120

prod() can also work with seq() to compute the product of consecutive numbers in a specified range:

Example

Compute the product from 3 to 8

result

<-

prod

(

3

:

8

)

print

(

result

)

Equivalent to 34567*8

print

(

3

4

5

6

7

8

)

The output of the code above is:

[1] 20160

[1] 20160

R Language Examples R Language Examples