rriverplot

Sum each list of numerical values within a list


I would like to attach values to labels in a riverplot in R

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 )) 

I am aware of a function that would reduce (or sum) one element of a list like this: Reduce("+",edges$A)

Is there a way of reducing such a list of lists of values to a dataframe or so that I could get the sums:

Node Sum
A 15
B 10
C 20
D 13
E 12 

Edit:

I just realised there is a confusion: It looks like I need two outputs and it may be a little more complicated: 1. if 'edges' list has a sublist with a category name, sum up 2. if not, get the sum of all occurences of this item

Case 1: Categories A, B, C (these are the starting nodes) Case 2: Categories D, E (these are the end nodes in a riverplot)

I am sorry for the confusion.


Solution

  • I think you can do

    lapply(edges, function (x) sum(unlist(x)))
    

    This returns a list. Using sapply will simplify the result to a vector.