1

I have a vector, which contains several NaNs. For example,

d=c(NaN,2,3,4,4,2,4,7,NaN,NaN,8,5,6,NaN)

I would like to do some expolation to replace NaNs. The difficulty for me is that I do not know how many NaNs I have and where they are.

Thank you very much.

mym123
  • 11
  • 3

2 Answers2

1

You can perform linear interpolation using zoo functions.

d=c(NaN,2,3,4,4,2,4,7,NaN,NaN,8,5,6,NaN)

zoo::na.spline(d)
# [1]  1.86  2.00  3.00  4.00  4.00  2.00  4.00  7.00  9.08  9.61  8.00  5.00  6.00 15.06

zoo::na.approx(d, na.rm = FALSE)
#[1]   NA 2.00 3.00 4.00 4.00 2.00 4.00 7.00 7.33 7.67 8.00 5.00 6.00   NA
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

We can use na_interpolation from imputeTS with several option: see: https://www.rdocumentation.org/packages/imputeTS/versions/3.2/topics/na.interpolation

library(imputeTS)
na_interpolation(d, option = "linear", maxgap = Inf)

Output:

> na_interpolation(d, option = "linear", maxgap = Inf)
 [1] 2.000000 2.000000 3.000000 4.000000 4.000000 2.000000 4.000000 7.000000 7.333333 7.666667 8.000000 5.000000 6.000000
[14] 6.000000
TarJae
  • 72,363
  • 6
  • 19
  • 66