How to Calculate Product in R

In maths, a product is an outcome of multiplication or an expression that classifies factors to be multiplied. In short, the product in math is described as the result obtained after the arithmetic operation of multiplication. For example, in the R language, we can calculate the product of vectors. Let’s see how to do that.

Calculate product in R

To calculate the product in R, use the prod() function. The prod() is a built-in R function that takes numeric, complex, or logical vectors as arguments and returns the multiplication results of all the values present in 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

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.

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.

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 NA value, then it will return NA without any doubt.

But, if we pass na.rm = TRUE, then 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 it contains an NA value.

That’s it for this tutorial.

See also

crossprod in r

sum in r

mean in r

median in r

average in r

Leave a Comment