Count Number of List Elements in R (original) (raw)
Last Updated : 17 May, 2025
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.
1. Creating a List
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.
R `
a1 <- list("Geeks", "For", "Geeks") print(length(a1))
`
2. Empty List
Here, we create an empty list and count its elements, which will be 0.
R `
empty_list <- list() print(length(empty_list))
`
3. List with Range, Vector, and Character Vector
Here we combine numeric and character vectors into a single list and prints the total number of top level list elements.
R `
vec <- 1:5 my_range <- seq(3, 9, by = 2) my_list <- list(numbers = vec, sequence = my_range, fruits = c("apple", "banana", "orange")) print(my_list) print(length(my_list))
`
Output
$numbers [1] 1 2 3 4 5
$sequence [1] 3 5 7 9
$fruits [1] "apple" "banana" "orange"
[1] 3
4. Counting Elements in Nested List Using lengths()
Now we will use lengths() function to get the number of elements inside each top level element of the list (nested lists).
R `
values <- 10:50 names <- c("sravan", "bobby", "ojaswi", "gnanu") data1 <- list(1, 2, 3, 4, 5) data <- list(a1 = values, a2 = names, a3 = data1) print(lengths(data))
`
5. Using length() and lengths() simultaneously
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. R `
data1 <- list(1, 2, 3, 4, 5) data2 <- list("a", 'b', 'c') data <- list(a1 = data1, a2 = data2) return(length(data)) print("-----------------------------") return(lengths(data))
`
**Output:
2
[1] "-----------------------------"
a1: 5
a2: 3