R prod() Function - Calculating Product
The R prod() function is used to calculate 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:
xInput vector.
na.rmBoolean value, defaults to FALSE, indicating whether to remove missing values NA.
Example
# Create a vector
x <- c(1, 2, 3, 4, 5)
# Calculate the product (equivalent to 5!)
result.prod <- prod(x)
print(result.prod)
# Verification: compare with factorial(5)
print(factorial(5))
x <- c(1, 2, 3, 4, 5)
# Calculate the product (equivalent to 5!)
result.prod <- prod(x)
print(result.prod)
# Verification: compare with factorial(5)
print(factorial(5))
Executing the above code produces the following result:
[1] 120 [1] 120
prod() can also be used with seq() to calculate the product of consecutive numbers within a specified range:
Example
# Calculate the product from 3 to 8
result <- prod(3:8)
print(result)
# Equivalent to 3*4*5*6*7*8
print(3 * 4 * 5 * 6 * 7 * 8)
result <- prod(3:8)
print(result)
# Equivalent to 3*4*5*6*7*8
print(3 * 4 * 5 * 6 * 7 * 8)
Executing the above code produces the following result:
[1] 20160 [1] 20160Other Extensions
R Language Examples