Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum list elements with the same name?

I´m looking for a solution to this problem: I have a list of lists like this

sample = list("element1" = list("term1"=0.5, "term2"=1, "term3"= 4, "term1"= 0.5), "element2" = list("term23"=5, "term1"=2, "term23"=4))

For each list of the outer list I would like to sum values with the same name. So the desired output is

desired_output = list("element1" = list("term1"=1, "term2"=1, "term3"= 4), "element2" = list("term23"=9, "term1"=2))

Actually, I thought of using something like this

result = lapply(sample, function(l) aggregate(l, by = list(names(l)), FUN = sum))

but that gives me an error. Any ideas about this? Thanks in advance.

like image 313
WinterMensch Avatar asked Jan 05 '18 08:01

WinterMensch


2 Answers

If you want to use aggregate, here is an idea that produces a slightly different output than your expected one

lapply(sample, function(i){s1 <- stack(unlist(i)); 
                           aggregate(values ~ ind, s1, sum)})

#or all in one line (compliments of Ronak Shah)
lapply(sample, function(x) aggregate(values~ind, stack(x), sum))

#Or use xtabs to output your expected result (compliments of akrun)
lapply(sample, function(x) as.list(xtabs(values~ind, stack(x))))

which gives,

$element1
    ind values
1 term1      1
2 term2      1
3 term3      4

$element2
     ind values
1 term23      9
2  term1      2
like image 181
Sotos Avatar answered Nov 01 '22 15:11

Sotos


Try this:

lapply(sample, function(y) {lapply(split(y,names(y)), function(x) {Reduce("+", x) })})

Output:

$element1
$element1$term1
[1] 1

$element1$term2
[1] 1

$element1$term3
[1] 4


$element2
$element2$term1
[1] 2

$element2$term23
[1] 9

Hope this helps!

like image 22
Florian Avatar answered Nov 01 '22 14:11

Florian