2
$\begingroup$

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?

$\endgroup$
2
$\begingroup$

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

$\endgroup$
  • $\begingroup$ thanks!! that is exactly what I was looking for (and should have found myself) $\endgroup$ – iav Feb 12 at 7:23
  • 1
    $\begingroup$ @iav, my pleasure. Thank you for the accept. $\endgroup$ – kglr Feb 12 at 7:25

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.