Search code examples
rlistlapplysapply

Get the index of the largest list in a list of list in R


This question builds off of this other question: get the lengths of element of lists of list in R.

Once we get the lengths of the elements in the lists of lists, how do we get the index of the largest list?

My lists of lists d looks like:

d <- list( list(level = c(1), x = c(10,20,30,40), y = c(55,44,33,22)), 
list(level = c(1), x = c(50,70,23,53, 43), y = c(80,23,54,30, 43)), 
list(level = c(1), x = c(30), y = c(90)))

Here's a visual representation

[[1]]
[[1]]$level
[1] 1

[[1]]$x
[1] 10 20 30 40

[[1]]$y
[1] 55 44 33 22

[[2]]
[[2]]$level
[1] 1

[[2]]$x
[1] 50 70 23 53 43

[[2]]$y
[1] 80 23 54 30 43

[[3]]
[[3]]$level
[1] 1

[[3]]$x
[1] 30

[[3]]$y
[1] 90

The first list of lists has a total of 9 elements, the second list of lists has a total of 11 elements, the third lists of lists has 3 elements.

I'm looking for a command that will return the index 2 since that has the list of lists has the most elements.


Solution

  • We loop through the list, extract either the 'x' or 'y' component and get the lengths of it, use that to create a logical index for filtering the lst

    l1 <- lengths(sapply(d, `[`, 'x'))
    d[l1== max(l1)]
    
    #[[1]]
    #[[1]]$level
    #[1] 1
    
    #[[1]]$x
    #[1] 50 70 23 53 43
    
    #[[1]]$y
    #[1] 80 23 54 30 43
    

    If this has to take into account the total number of elements, loop through the list ('d') unlist and get the lengths

    l1 <- lengths(lapply(d, unlist))
    d[l1 == max(l1)]