You can use the following methods to count the number of elements in a list in R:
Method 1: Count Number of Elements in List
length(my_list)
Method 2: Count Number of Elements in Specific Component of List
length(my_list[[3]])
Method 3: Count Number of Elements in Each Component of List
lengths(my_list)
The following examples show how to use each method in practice with the following list in R:
#define list
my_list #view list
my_list
$x
[1] 1 4 4 5 7 8
$y
[1] "Hey"
$z
[1] A B C D
Levels: A B C D
Example 1: Count Number of Elements in List
We can use the length() function to simply count how many elements are in the list:
#count number of elements in list
length(my_list)
[1] 3
We can see that there are 3 elements in the list.
Example 2: Count Number of Elements in Specific Component of List
We can use the length() function combined with double brackets to count the number of elements in a specific component of the list.
For example, we can use the following code to count how many elements are in the third component of the list:
#count number of elements in third component of list
length(my_list[[3]])
[1] 4
We can see that there are 4 elements in the third component of the list.
Specifically, the four values are A, B, C, and D.
Example 3: Count Number of Elements in Each Component of List
We can use the lengths() function to count the number of elements in each individual component of the list:
#count number of elements in each component of list
lengths(my_list)
x y z
6 1 4
From the output we can see:
- x has 6 elements (1, 4, 4, 5, 7, 8)
- y has 1 element (‘hey’)
- z has 4 elements (‘A’, ‘B’, ‘C’, ‘D’)
Note that we could also use the sum() function with the length() function to count the total number of individual elements in the entire list:
#count total number of individual elements in entire list
sum(lengths(my_list))
[1] 11
We can see that there are 11 total elements in the entire list.
Additional Resources
The following tutorials explain how to use other common functions in R:
How to Use the replace() Function in R
How to Use split() Function in R
How to Use the View() Function in R