Change an observation in a TimeSeries

4

2

What is the proper way to change one observation in a TimeSeries object?

Let's say there a time series:

ts = TimeSeries[Transpose[{Range[10], RandomReal[{0, 1}, 10]}]]

Now, I need to alter the 2nd observation to some value like 3.

ts[2] = 3
(*produces error: TemporalData is Protected *)

Now, I can define something like this:

  TimeSeriesAssign[ts_, v_] := TimeSeries[
     ts["DatePath"] /. {DateObject[First@v], _} :> {DateObject@First@v, 
       Last@v}]

...which does the job:

ts = TimeSeriesAssign[ts, {2, 3}]
ts[2]
(*3*)

But is there a better, preferably built-in way to make assignments to TimeSeries object's observations?

iav

Posted 2019-02-11T10:47:39.970

Reputation: 1 875

Answers

4

You can use TimeSeriesInsert:

  • TimeSeriesInsert[tseries, {t, v}] inserts a value v at time t in the time series tseries.
  • If a value is already present at time t it will be replaced by v.
SeedRandom[1]
ts = TimeSeries[Transpose[{Range[10], RandomReal[{0, 1}, 10]}]];
ts2 = TimeSeriesInsert[ts, {2, 3}];

ListLinePlot[{ts, ts2}, PlotRange -> All, 
 PlotMarkers -> {Automatic, 10}, PlotLegends -> {"ts", "ts2"}]

enter image description here

You can check if a value at time t exists before making the change:

ClearAll[tsInsert]
tsInsert = If[MemberQ[ts["Times"], First@#2], TimeSeriesInsert[#, #2], #] &;

tsInsert[ts, {2, 3}] == ts2

True

kglr

Posted 2019-02-11T10:47:39.970

Reputation: 302 076

1thanks!! that is exactly what I was looking for (and should have found myself) – iav – 2019-02-12T07:23:01.743

1@iav, my pleasure. Thank you for the accept. – kglr – 2019-02-12T07:25:43.197