Open In App

Find product of vector elements in R

Improve
Improve
Like Article
Like
Save
Share
Report

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:

R




# declaring a floating point vector 
vec <- c(1.1,2,3.2,4)
size = length(vec)
  
# initializing product as 1
prod = 1
  
# looping over the vector elements
for(i in 1:size)
 {
  # multiplying the vector element at ith index 
  # with the product till now
  prod = vec[i]*prod
 }
print("Product of vector elements:")
  
# in-built application of prod function
print(prod)


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:

R




# declaring a floating point vector 
vec <- c(1.1,2,NA,11,4)
size = length(vec)
  
# initializing product as 1
prod = 1
  
# looping over the vector elements
for(i in 1:size)
 {
  # multiplying the vector element at
  # ith index with the product till now
  prod = vec[i]*prod
  cat("Product after iteration:"
  print(prod)
 }
print("Final product of vector elements:")
  
# in-built application of prod function
print(prod)


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:

R




# declaring a integer vector 
vec <- c(1,2,3,4)
print("Product of vector elements:")
  
# in-built application of prod function
print(prod(vec))


Output

[1] “Product of vector elements:”

[1] 24



Last Updated : 26 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads