R prod() Function - Computing Products
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:
-
x Input vector.
-
na.rm A boolean value, default FALSE, sets whether to remove missing values NA.
Example
Create a vector
x
<-
c
(
1
,
2
,
3
,
4
,
5
)
Compute the product (equivalent to 5!)
result.
prod
<-
prod
(
x
)
(
result.
prod
)
Verification: compare with factorial(5)
(
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
)
(
result
)
Equivalent to 34567*8
(
3
4
5
6
7
8
)
The output of the code above is:
[1] 20160
[1] 20160
R Language Examples