VOOZH about

URL: https://www.geeksforgeeks.org/r-language/count-number-of-list-elements-in-r/

⇱ Count Number of List Elements in R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Number of List Elements in R

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:

  1. length() to count the number of top-level elements in a list.
  2. 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.


Output
[1] 3

2. Empty List

Here, we create an empty list and count its elements, which will be 0.


Output
[1] 0

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.


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).


Output
a1 a2 a3 
41 4 5 

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.

Output:

2

[1] "-----------------------------"

a1: 5
a2: 3

Comment

Explore