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, 

...which does the job:

ts = TimeSeriesAssign[ts, {2, 3}]

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


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.
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:

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

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


  • $\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 agree to our terms of service, privacy policy and cookie policy

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