# Can one force TimeSeries to add instead of average values with identical timestamps?

I have a list of time-value pairs of the form {{t1,v1},{t2,v2},{t3,v3},...} that I'd like to turn into a TimeSeries object.

The problem is, some of the time values are identical, meaning the list actually looks more like

{{t1,v1},{t2,v2a},{t2,v2b},{t3,v3},...}.

If I simply operate on the list with TimeSeries, Mathematica averages the values corresponding to the identical times, thus producing

{{t1,v1},{t2,(v2a+v2b)/2},{t3,v3},...}.

But I want it to add those values instead, thereby producing

{{t1,v1},{t2,(v2a+v2b)},{t3,v3},...}.

Alas, I can't find an option for TimeSeries which controls this behavior. Does anyone know if such an option exists?

If that option does not, can anyone suggest an elegant solution to combine these values before wrapping them with TimeSeries? I vaguely recall seeing a simple line of code to do just that somewhere here before, but I've been unable to find that, too.

Meanwhile, I'll continue working the problem myself, and I'll post any solutions I come up with.

Thanks!

----------UPDATE----------

I came up with the following workaround:

If[Length@# > 1, {#[[1, 1]], Total@#[[All, 2]]}, #[[1]]] & /@
GatherBy[#, First] &@{{t1, v1}, {t2, v2a}, {t2, v2b}, {t3, v3}}


which outputs {{t1, v1}, {t2, v2a + v2b}, {t3, v3}}.

I can then hit that with TimeSeries.

But is there a more elegant solution?

• This seems to be an oversight in the language design IMHO. TimeSeries does something undocumented (taking the average) when it encounters duplicate timestamps, instead of allowing the user to supply a function. TimeSeriesInsert will replace any existing value with the same timestamp, when it too could have allowed the user to supply a function. Commented Jul 10, 2020 at 18:11
• To whom do I complain? ;-) Commented Jul 10, 2020 at 18:26
• I just asked about this in the chat room :P Commented Jul 10, 2020 at 18:53

## 1 Answer

I don't know if you can do this with TimeSeries, but you can do it yourself with GroupBy like this:

data = SortBy[First] @ Table[{RandomInteger[{0, 10}], RandomReal[]}, 20];
ts = TimeSeries[GroupBy[data, First -> Last, Total]]

• Nice. I've never worked with associations before, but they seem quite useful--especially for my current project. Thanks! Commented Jul 10, 2020 at 17:54
• @AaronEiben Definitely make sure to learn about them. They're super useful for lots of things. Commented Jul 10, 2020 at 17:58
• Okay, I'm giving this the win since the desired option for TimeSeries doesn't seem to exist, and for sending me down the rabbit holes of Association and Dataset. (Though funnily enough, these constructs might render the original need moot.) Commented Jul 11, 2020 at 16:17