Replaces NA values in a ts object with linearly interpolated values, using the non-missing observations as anchor points. The result preserves the original time series' start time and frequency.

removenas(y)

Arguments

y

A univariate time series object of class ts. An error is raised if y is not a ts object.

Value

A ts object of the same length, start, and frequency as y, with internal NA values replaced by linearly interpolated values. If y has no missing values, y is returned as-is.

Details

If y contains no missing values, it is returned unchanged. Otherwise, stats::approx is used to linearly interpolate the missing entries based on the time index (stats::time(y)) and the non-missing values, evaluated at every time point in y (so any NA at the very start or end of the series may itself remain NA, per the default behavior of approx, since there are no bracketing points to interpolate from). The interpolated values are then reassembled into a new ts object with the same start and frequency as the input.

Examples

if (FALSE) { # \dontrun{
y <- ts(c(1, 2, NA, 4, 5, NA, 7), start = c(2020, 1), frequency = 12)
removenas(y)
} # }