# Change an observation in a TimeSeries

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?

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"}]


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

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