VOOZH about

URL: https://www.geeksforgeeks.org/r-language/find-product-of-vector-elements-in-r/

⇱ Find product of vector elements in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find product of vector elements in R

Last Updated : 26 Mar, 2021

In this article, we will see how to find the product of vector elements in R programming language.

Method 1: Using iteration

Approach

  • Create dataframe
  • Iterate through the vector
  • Multiply elements as we go
  • Display product

The following code snippet indicates the application of for loop over decimal point vector. The product obtained is also of the decimal type. 

Example:

Output

[1] "Product of vector elements:"

[1] 28.16

The other example demonstrates the behavior of any mathematical operation on a missing, that is NA value. The product returned is NA, in such a case.

Example 2:

Output

Product after iteration:[1] 1.1

Product after iteration:[1] 2.2

Product after iteration:[1] NA

Product after iteration:[1] NA

Product after iteration:[1] NA

[1] "Final product of vector elements:"

[1] NA

Method 2: Using prod()

prod() function in R is an in-built method which can directly compute the multiplicative product of the individual elements in the vector which are specified as its arguments. In case, a single argument is present, it computes the multiplicative output of the individual elements of the vector. 

Syntax:

prod(vector)

Example:

Output

[1] "Product of vector elements:"

[1] 24

Comment

Explore