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.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With