Superbest
Superbest

Reputation: 26592

Interpolate missing values of a data frame

I have a dataset like this:

x   y   z
1   1   0.954
1   3   0.134
1   30  0.123
2   1   0.425
2   3   0.123
2   30  0.865
5   1   0.247
5   3   0.654
5   30  0.178

Let's think of this as the height of a surface sampled at 9 points over a 4x29 field. Suppose I want to fill in the missing values by interpolating (linear is fine), so that I end up with a z value for every (integer) x in [1,5] and every y in [1,30]. I want the result to still be a data frame with the same structure.

How can I do this in R?

Upvotes: 1

Views: 1453

Answers (1)

Jubbles
Jubbles

Reputation: 4570

I'll take the previous lack of answer as a gift :)

#akima_0.5-12
library(akima)

my_df <- data.frame(
    x = c(rep(1, 3), rep(2, 3), rep(5, 3)),
    y = rep(c(1, 3, 30), 3),
    z = c(0.954, 0.134, 0.123, 0.425, 0.123, 0.865, 0.247, 0.654, 0.178)
)

my_op <- interp(
    x = my_df$x,
    y = my_df$y,
    z = my_df$z,
    xo = 1:5, # vector of x coordinates to use in interpolation
    yo = 1:30, # vector of y coordinates to use in interpolation
    linear = TRUE # default interpolation method
)

my_op$z # matrix of interpolated z coordinates, (row, col) correspond to (x, y)

ind <- which(!is.nan(my_op$z), arr.ind = TRUE)
desired_output <- data.frame(
    x = ind[, 1],
    y = ind[, 2],
    z = as.vector(my_op$z) # data are organized column-by-column
)

Upvotes: 1

Related Questions