Count the number of objects in a list

Does anyone know a function R that will return the number of elements in a list?

+74
list r count
Nov 16 '09 at 6:58
source share
5 answers
+126
Nov 16 '09 at 7:08
source share

Tip for R newbies like me: beware, the following is a list of one object :

 > mylist <- list (1:10) > length (mylist) [1] 1 

In this case, you are not looking for the length of the list, but its first element:

 > length (mylist[[1]]) [1] 10 

This is the "true" list:

 > mylist <- list(1:10, rnorm(25), letters[1:3]) > length (mylist) [1] 3 

In addition, it seems that R treats data.frame as a list:

 > df <- data.frame (matrix(0, ncol = 30, nrow = 2)) > typeof (df) [1] "list" 

In this case, you may be interested in ncol() and nrow() , rather than length() :

 > ncol (df) [1] 30 > nrow (df) [1] 2 

Although length() will also work (but this is a trick when your data.frame has only one column):

 > length (df) [1] 30 > length (df[[1]]) [1] 2 
+62
Jan 29 '14 at 23:26
source share

I spent years trying to figure it out, but it's easy! You can use length(ยท) . length(mylist) tells you how many objects mylist contains.

... and just realized that someone had already answered this - sorry!

+10
Jun 14 '10 at 13:26
source share

Let me create an empty list (not necessary, but good to know):

 > mylist <- vector(mode="list") 

Put something into it - 3 components / indexes / tags (everything you want to name), each with a different number of elements:

 > mylist <- list(record1=c(1:10),record2=c(1:5),record3=c(1:2)) 

If you are only interested in the number of components in the list, use:

 > length(mylist) [1] 3 

If you are interested in the length of the elements in a specific component of the list, use: (both here refer to the same component)

 length(mylist[[1]]) [1] 10 length(mylist[["record1"]] [1] 10 

If you are interested in the length of all elements in all components of the list, use:

 > sum(sapply(mylist,length)) [1] 17 
+7
Nov 19 '15 at 17:33
source share

You can also use unlist() , which is often useful for handling lists:

 > mylist <- list(A = c(1:3), B = c(4:6), C = c(7:9)) > mylist $A [1] 1 2 3 $B [1] 4 5 6 $C [1] 7 8 9 > unlist(mylist) A1 A2 A3 B1 B2 B3 C1 C2 C3 1 2 3 4 5 6 7 8 9 > length(unlist(mylist)) [1] 9 

unlist () is an easy way to perform other functions in lists, for example:

 > sum(mylist) Error in sum(mylist) : invalid 'type' (list) of argument > sum(unlist(mylist)) [1] 45 
+3
Jan 30 '17 at 20:27
source share



All Articles