Calculate Cumulative Product in R (Example) | cumprod() Function

 

In this article, I’ll show how to calculate cumulative products using the cumprod function in the R programming language.

Table of contents:

Let’s dive right in…

 

Creation of Example Data

Initially, we have to define some data that we can use in the exemplifying syntax later on:

x <- 1:10                      # Create example vector
x                              # Print example vector
#  [1]  1  2  3  4  5  6  7  8  9 10

As you can see based on the previous RStudio console output, our example data is a vector object containing ten integer values ranging from 1 to 10.

 

Example: Calculate Cumulative Product Using cumprod() Function

This example shows how to compute the cumulative product of a vector object in R.

For this task, we can apply the cumprod function to our example vector as shown below:

x_cumprod <- cumprod(x)        # Apply cumprod function
x_cumprod                      # Print cumulative products
# [1]    1       2       6      24     120     720
# [7] 5040   40320  362880  3628800

The previous output of the RStudio console shows the cumulative products that correspond to our input vector.

Note that we could apply the same syntax to a data frame column as well.

 

Video & Further Resources

If you need further information on the R programming syntax of this article, I recommend having a look at the following video on my YouTube channel. I show the R code of this article in the video:

 

 

In addition, you may have a look at the other articles that I have published on this website. You can find a selection of tutorials below:

 

In summary: In this R programming article you have learned how to apply the cumprod function. In case you have additional questions, let me know in the comments below.

 

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.

The maximum upload file size: 2 MB. You can upload: image. Drop file here

Top