Count Number of List Elements in R
Last Updated :
11 Mar, 2024
In this article, we are going to find the length of a list in R and count the elements in a list and elements in a nested list in R Programming Language. So we are going to use length() and lengths() to find the length of the list in R.
Steps –
- Create a list with vectors/list/range operator
- Find the count of elements using the length and lengths function.
Syntax: list(value1,value2,…,value)
values can be range operator or vector.
Using length() function
The length function is used to count the elements in the list.
Syntax: length(listname)
return value: integer
Let’s create a list and find the length of list
R
a1 <- list ( "Geeks" , "For" , "Geeks" )
print ( length (a1))
|
Output:
[1] 3
Now let us create an empty list and find the length of list
R
empty_list<- list ()
print ( length (empty_list))
|
Output:
[1] 0
Let’s create a list using the range, vector, and list and find the length of list
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
For finding the length of each data in a list (nested list) we will use lengths() function
Syntax: lengths(list_name)
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 (data)
print ( lengths (data))
|
Output:
$a1
[1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
[29] 38 39 40 41 42 43 44 45 46 47 48 49 50
$a2
[1] "sravan" "bobby" "ojaswi" "gnanu"
$a3
$a3[[1]]
[1] 1
$a3[[2]]
[1] 2
$a3[[3]]
[1] 3
$a3[[4]]
[1] 4
$a3[[5]]
[1] 5
a1 a2 a3
41 4 5
R program count elements in a nested list
R
data1 = list (1, 2, 3, 4, 5)
data2 = list ( "a" , 'b' , 'c' )
data = list (a1 = data1, a2 = data2)
print (data)
print ( length (data))
print ( "-----" )
print ( lengths (data))
|
Output:
$a1
$a1[[1]]
[1] 1
$a1[[2]]
[1] 2
$a1[[3]]
[1] 3
$a1[[4]]
[1] 4
$a1[[5]]
[1] 5
$a2
$a2[[1]]
[1] "a"
$a2[[2]]
[1] "b"
$a2[[3]]
[1] "c"
[1] 2
[1] "-----"
a1 a2
5 3
Share your thoughts in the comments
Please Login to comment...