TransWikia.com

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

Mathematica Asked on January 14, 2021

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?

One 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]]

Correct answer by Sjoerd Smit on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP