rlistriverplot

Sum items in sub-lists on categories they belong to, accross the main list


I would like to attach values to labels in a riverplot in R. This is the second (confusing) part of my problem that I decided to split to two questions first is: Sum each list of numerical values within a list

I have a list of lists of values, which is required to show flows between nodes, like this:

edges <- list( A= list( C= 10, E= 5 ), 
               B= list( C= 10 ), 
               C=list(D = 13, E = 7 )) 

Question: How to achieve the sums of items in sub-lists, accross the whole list, like:

C 20   
D 13
E 12 

I imagine the items should be first extracted to a data-frame, and then summarised. Or is there some formula that would decompose the sublists and then sum items contained in them according to categories (C, D, E).

I was wondering about using lapply sapply functions but doing it accross several sublists seems to be very complicated.


Solution

  • library(data.table)
    
    colSums(rbindlist(edges, fill=T), na.rm=T)
    # C  E  D 
    #20 12 13 
    

    Or:

    library(dplyr)
    
    colSums(bind_rows(edges), na.rm=T)
    # C  E  D 
    #20 12 13