Combining values in one column (or part) when values in another column (or part) match
Here's another one to consider:
{#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[Flatten[data, 1], First]
GatherBy...
gathers pairs with the same AbsoluteDate
.
{#[[1, 1]], Total[#[[All, 2]]]} & /@
returns {date, totVal} for each date.
The following also works (though its a bit messy to look at) and will probably be faster than pattern matching if you have large input data.
Transpose[{#[[All, 1, 1]],
Total[#[[All, All, 2]], {2}]}] &[#] & /@ (GatherBy[#, First] & /@
data)
EDIT:
I should point out that there are at least a couple of different problems being solved in the answers posted here. The results posted by myself and @RM attempt to preserve the structure of the original data and so do not gather like dates if they are present in multiple sublists.
Answers posted by @David Carraher and @rcollyer ignore the structure of the original data and gather all like dates.
I'm not sure which is the correct approach in this case but it felt worth pointing out the difference.
Assuming that you did not intend to add an extra layer of lists in your data,
for this type of manipulation, I'm a fan of Reap
and Sow
:
Reap[ Sow[#2, #1]& @@@ Flatten[data,1], _, {#1,Total[#2]}&][[2]]
(* {{3542313600, 175}, {3542918400, 175}, {3544128000, 450},
{3544732800, 450}, {3545337600, 900}, {3545942400, 450},
{3546547200, 450}, {3547152000, 0}}
*)
If it wasn't mistaken, we need to Map
the above onto each data set:
Reap[ Sow[#2, #1]& @@@ #, _, {#1,Total[#2]}&][[2]]& /@ data
(* {{{3542313600, 175}, {3542918400, 175}},
{{3544128000, 450}, {3544732800, 450}, {3545337600, 900},
{3545942400, 450}, {3546547200, 450}, {3547152000, 0}}}
*)