0

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.

www
  • 38,575
  • 12
  • 48
  • 84
Jacek Kotowski
  • 620
  • 16
  • 49

2 Answers2

3
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 
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
1

We can use base R

un1 <- unlist(edges)
tapply(un1, sub(".*\\.", "", names(un1)), FUN = sum)
#  C  D  E 
# 20 13 12 
akrun
  • 874,273
  • 37
  • 540
  • 662