NamelessGods
NamelessGods

Reputation: 197

Interpolation for missing values

Right now I'm doing this project which linearly interpolates the values for the missing y values using the existing data. Here is the basic idea: vector y is the y values in the data set:

y <- c(1, NA, NA, 2, 3, 4, NA, 5)

the x values are

x <- 1:8

What I want is to linearly interpolate the values for NA in y using the two non-zero data points closest to the NA spot and the corresponding x values, i.e. for spot 2, the y value would be interpolated using the x and y values in spot 1 and 4, namely(1,1) and (4,2). The only restriction is no loops are allowed. Anyone help please?

Upvotes: 0

Views: 696

Answers (1)

MrFlick
MrFlick

Reputation: 206566

Seems like a good candiate for approxfun which does linear interpolation. Just fit the interpolation using the non-NA values

y <- c(1, NA, NA, 2, 3, 4, NA, 5)
x <- 1:8

f<-approxfun(x[!is.na(y)], y[!is.na(y)])
f(x)
# [1] 1.000000 1.333333 1.666667 2.000000 3.000000 4.000000 4.500000 5.000000

Upvotes: 3

Related Questions