10 19 25 X 14", stringsAsFactors=FALSE)
y <- c(t(as.matrix(y, ncol=5)))
y[y == "X"] <- NA
y <- as.numeric(y)
x <- c(1:length(y))
yNaIndex <- which(
is.na(y))
# method 1. Using approxfun {stats}
myApprox <- approx(x, y, xout=yNaIndex) # list
y[yNaIndex] <- myApprox$y
# method 2. Using linear interpolation, y=mx+b
yLinearInterpolation <- c()
for (i in yNaIndex) {
m <- (y[i+1] - y[i-1])/(x[i+1] - x[i-1]) # slope
b <- y[i-1] - (m*x[i-1]) # intercept
yLinearInterpolation <- c(yLinearInterpolation, m*i + b)
}
y[yNaIndex] # approxfun
yLinearInterpolation # linear interpolation (same as approxfun function)
# visualization
plot(x, y, type="b", main="Linear interpolation")
points(myApprox, col="red", pch=16)
# end