Sum of List Elements in R (2 Examples)
In this tutorial you’ll learn how to sum list items in the R programming language.
The content of the post looks as follows:
You’re here for the answer, so let’s get straight to the examples.
Construction of Example Data
Initially, let’s construct some example data:
my_list <- list(1:5, # Create example list c(8, 3, 5, 3, 6), 9:5) my_list # Print example list # [[1]] # [1] 1 2 3 4 5 # # [[2]] # [1] 8 3 5 3 6 # # [[3]] # [1] 9 8 7 6 5
The previous output of the RStudio console shows the structure of the exemplifying data: We have created a list containing three list elements. Each of these list elements contains a vector of five numeric values.
Example 1: Calculate Sum Between List Elements Using Reduce() Function
This example shows how to compute the sum of the corresponding vector elements between the different elements of a list, i.e. the sum of the first index position of each list element, the sum of the second index position, and so on…
To achieve this, we can apply the Reduce function as shown in the following R code:
Reduce("+", my_list) # Sum between list elements # [1] 18 13 15 13 16
The previous R syntax has returned a vector consisting of five values. Each of these values is the sum of the corresponding list elements (e.g. 1 + 8 + 9 = 18).
Example 2: Calculate Sum Within List Element Using sapply() Function
Example 2 shows how to return the sum of the numerical values within each list element, i.e. the sum of all values in the first list element, the sum of all values in the second list element, and so on…
For this, we can use the sapply function as shown below:
sapply(my_list, sum) # Sum within list element # [1] 15 25 35
The previous output shows the sum for every list item in our list (e.g. 1 + 2 + 3 + 4 + 5 = 15).
Video, Further Resources & Summary
Do you want to know more about the calculation of the sum within and between list items? Then I recommend having a look at the following video which I have published on my YouTube channel. In the video, I’m explaining the R code of this tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may have a look at some of the other posts on this website.
- Extract Names of List Elements
- Count Number of List Elements in R
- How to Add New Elements to a List
- Convert Data Frame Columns to List Elements
- All R Programming Examples
This page has illustrated how to sum list elements in R programming. Let me know in the comments, if you have any further questions.
Statistics Globe Newsletter