Search code examples
rnested-listssapply

How to run a function through multiple sublists in R?


I have a complex nested list named AllVotes that you can find here (in .rds) :

https://github.com/JMcrocs/MEPVote/blob/master/FinalVotes.rds

I am trying to collect all the mepid, a named number stored in the sublists AllVotes[[x]]$votes$'+'$groups. Thanks to a previous question here I am able to do that for one list (the [[1]] list) but I would like to do it for all the list of my nest list from [[1]] to [[2336]].

#For the list [[1]]
Result = c(unlist( sapply ( names ( AllVotes[[1]]$votes$'+'$groups ), 
                   function(x) unlist( AllVotes[[1]]$votes$'+'$groups[[x]] ) ) ),
unlist( sapply ( names ( AllVotes[[1]]$votes$'-'$groups ), 
                   function(x) unlist( AllVotes[[1]]$votes$'-'$groups[[x]] ) )),
unlist( sapply ( names ( AllVotes[[1]]$votes$'0'$groups ), 
                   function(x) unlist( AllVotes[[1]]$votes$'0'$groups[[x]] ) )))

How can I do that? Thank you in advance !

PS : Sorry if the question is not perfect I am two weeks new to programming (and Overflow).


Solution

  • You can simplify the code to:

    res <- lapply(AllVotes, function(x){
      unlist(lapply(c('+', '-', '0'), function(y){
        x$votes[[y]]$groups
      }))
    })
    

    which gives the same output as @Duck's answer.

    all.equal(res, List, check.attributes = F)
    # [1] TRUE