Calculate Product of Vector & Data Frame in R (Example)

 

In this article, I’ll show how to compute the product of a vector, and the rows and columns of a data frame in R programming.

The post looks as follows:

Here’s the step-by-step process…

 

Example 1: Calculate Product of Vector Elements

This example illustrates how to multiply all elements of a vector in R.

For this, we first have to create an example vector:

vec <- 1:5                      # Create example vector
vec                             # Print example vector
# [1] 1 2 3 4 5

The previous RStudio console output shows that our vector contains five numeric elements ranging from the values 1 to 5.

Next, we can apply the prod function to calculate the product of our vector elements as shown below:

prod(vec)                       # Calculate product of vector elements
# [1] 120

As you can see, the product of the elements in our example vector is 120.

 

Example 2: Calculate Product of Data Frame Rows & Columns

In Example 2, I’ll explain how to calculate the product of data frame rows and columns.

First, we have to create a data frame in R:

data <- data.frame(x1 = 1:5,    # Create example data
                   x2 = 11:15,
                   x3 = 9:5)
data                            # Print example data

 

Table 1 prod function

 

The previous output shows that our data frame contains five rows and three numeric columns.

If we want to multiply the elements of each row, we can use the apply function in combination with the prod function as shown below:

apply(data, 1, prod)            # Calculate product of rows
# [1]  99 192 273 336 375

If we want to calculate the product by column, we can use the following R code:

apply(data, 2, prod)            # Calculate product of columns
#     x1     x2     x3 
#    120 360360  15120

Looks good!

 

Video, Further Resources & Summary

Do you need more information on the R programming codes of this article? Then you might have a look at the following video on my YouTube channel. I’m explaining the R programming codes of this article in the video.

 

The YouTube video will be added soon.

 

In addition, you might want to have a look at the other tutorials on this website. I have published numerous tutorials that are related to the calculation of the product of a vector, and the rows and columns of a data matrix already:

 

At this point, you should know how to calculate the product of a vector, and the rows and columns of a data matrix in the R programming language. Let me know in the comments section, if you have additional questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top