To calculate the product in R, you can use the “prod()” function. The prod() function in R is “used to calculate the product of the individual elements in the vector specified as its arguments”.
Syntax
prod(…, na.rm = FALSE)
Parameters
- …: They are numeric or complex, or logical vectors.
- na.rm: It is a logical argument. Whether missing values be removed or not.
Return value
It returns the product, a numeric (of type “double”) or complex vector of length one.
Example 1: Finding a product of the vector
Let’s define a numeric vector and calculate its product.
data <- 4:8
cat("The product of a vector is: ", "\n")
product <- prod(data)
cat(product)
Output
The product of a vector is:
6720
That’s it. This is how you calculate the product of a vector in R.
Example 2: Finding a product of complex vectors
To calculate the product of complex vectors in R, use the “prod()” function. The prod() method takes a complex vector as an argument and returns its product.
complex <- c(1+1i, 2+3i)
cat("The product of a complex vector is: ", "\n")
complexprod <- prod(complex)
cat(complexprod)
Output
The product of a complex vector is:
-1+5i
This is how you can calculate the product of complex vectors.
Example 3: Passing na.rm = FALSE
If na.rm is FALSE, an NA value in any of the arguments will cause a value of NA to be returned. Otherwise, NA values are ignored.
complex <- c(1+1i, NA)
cat("The product of a complex vector is: ", "\n")
complexprod <- prod(complex, na.rm = FALSE)
cat(complexprod)
Output
The product of a complex vector is:
NA
You can see that if we pass na.rm = FALSE and the vector contains an NA value, then it will return NA without any doubt.
But, if we pass na.rm = TRUE, it will ignore the NA value and calculate the remaining values’ product.
complex <- c(1+1i, NA)
cat("The product of a complex vector is: ", "\n")
complexprod <- prod(complex, na.rm = TRUE)
cat(complexprod)
Output
The product of a complex vector is:
1+1i
And we get the output even if it contains an NA value.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.