drastega
drastega

Reputation: 1773

How to interpolate vector by y in R

I have a vector with coordinates

x <- c(1, 3, 5, 7)
y <- c(2.6, 7.3, 6.8, 1.9)

I need to interpolate vector (x, y) by x and by y at the same time. By x I can do

approxfun(x, y)(1:7)

But how to interpolate by y? I need to obtain n = floor(abs(y1 - y2)) points between neighboring y1 and y2.

Upvotes: 1

Views: 425

Answers (1)

Waldi
Waldi

Reputation: 41260

You could use purrr::pmap combined with dplyr::lag to interpolate between x[i-1] and x[i].
For a linear interpolation between two points, it doesn't matter to cut the interval by x or by y, so that approxfun(x, y) still works :

library(dplyr)
library(purrr)

x <- c(1, 3, 5, 7)
y <- c(2.6, 7.3, 6.8, 1.9)


df <- data.frame(x=x,y=y)

df %>% mutate(xprev = lag(x),yprev=lag(y)) %>% 
  purrr::pmap(~with(list(...),{
    if (is.na(xprev)) {
      data.frame(x=x,y=y)
    } else {
      n <-  floor(abs(yprev-y)) + 2
      if (n>0) {
        xstep <- (x-xprev) / n  
        xsteps <- seq(xprev+xstep,x ,by = xstep )       
        data.frame(x=xsteps, y=approxfun(c(xprev,x),c(yprev,y))(xsteps))
      }
    }
  })) %>% bind_rows 
#>     x     y
#> 1 1.0 2.600
#> 2 1.5 3.775
#> 3 2.0 4.950
#> 4 2.5 6.125
#> 5 3.0 7.300
#> 6 5.5 5.575
#> 7 6.0 4.350
#> 8 6.5 3.125
#> 9 7.0 1.900

Upvotes: 2

Related Questions