Find product of vector elements in R
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
vec <- c (1.1,2,3.2,4)
size = length (vec)
prod = 1
for (i in 1:size)
{
prod = vec[i]*prod
}
print ( "Product of vector elements:" )
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
vec <- c (1.1,2, NA ,11,4)
size = length (vec)
prod = 1
for (i in 1:size)
{
prod = vec[i]*prod
cat ( "Product after iteration:" )
print (prod)
}
print ( "Final product of vector elements:" )
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
vec <- c (1,2,3,4)
print ( "Product of vector elements:" )
print ( prod (vec))
|
Output
[1] “Product of vector elements:”
[1] 24
Last Updated :
26 Mar, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...