Use na.approx
. There are some arguments that can be used to specify how to deal with NA's on the ends. It assumes that the data is equally spaced unless you use the x= argument to specify some other x values. See ?na.approx
for more details.
library(zoo)
y <- c(1, 2, NA, 4, 5, NA, 7)
na.approx(y)
## [1] 1 2 3 4 5 6 7
y2 <- c(NA, 1, NA, 2, NA)
na.approx(y2)
## [1] 1.0 1.5 2.0
na.approx(y2, na.rm = FALSE)
[1] NA 1.0 1.5 2.0 NA
na.approx(y2, rule = 2)
## [1] 1.0 1.0 1.5 2.0 2.0
# BOD comes with R. Create version where demand[5] is NA.
BOD2 <- transform(BOD, demand = replace(demand, 5, NA))
transform(BOD2, demand = na.approx(demand)) # without x=
## Time demand
## 1 1 8.3
## 2 2 10.3
## 3 3 19.0
## 4 4 16.0
## 5 5 17.9
## 6 7 19.8
transform(BOD2, demand = na.approx(demand, x = Time)) # with x=
## Time demand
## 1 1 8.30000
## 2 2 10.30000
## 3 3 19.00000
## 4 4 16.00000
## 5 5 17.26667
## 6 7 19.80000