![]() |
VOOZH | about |
In this article, we will explore how to count the number of elements in a list in R, including both simple and nested lists.
We'll use two key functions:
length() to count the number of top-level elements in a list.lengths() to count the number of elements within each top-level list component.These functions are helpful for navigating and analyzing lists in R, especially when dealing with nested structures.
To start, we can create a basic list using vectors, character data, or range sequences. Then we use length() to count the number of top-level elements.
[1] 3
Here, we create an empty list and count its elements, which will be 0.
[1] 0
Here we combine numeric and character vectors into a single list and prints the total number of top level list elements.
$numbers [1] 1 2 3 4 5 $sequence [1] 3 5 7 9 $fruits [1] "apple" "banana" "orange" [1] 3
lengths()Now we will use lengths() function to get the number of elements inside each top level element of the list (nested lists).
a1 a2 a3 41 4 5
We will try to understand the difference between length() and lengths() function by implementing the simultaneously. We can observe that:
length(data) counts the top level elements in the list.lengths(data) counts the number of elements in each nested list.Output:
2
[1] "-----------------------------"
a1: 5
a2: 3