如何在 R 中通过 y 插入向量
How to interpolate vector by y in R
我有一个带坐标的向量
x <- c(1, 3, 5, 7)
y <- c(2.6, 7.3, 6.8, 1.9)
我需要同时通过 x
和 y
对向量 (x, y) 进行插值。通过x
我能做到
approxfun(x, y)(1:7)
但是y
怎么插值呢?我需要在相邻 y1
和 y2
之间获得 n = floor(abs(y1 - y2))
点。
您可以使用 purrr::pmap
结合 dplyr::lag
在 x[i-1]
和 x[i]
之间进行插值。
对于两点之间的线性插值,将间隔削减 x
或 y
并不重要,因此 approxfun(x, y)
仍然有效:
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
我有一个带坐标的向量
x <- c(1, 3, 5, 7)
y <- c(2.6, 7.3, 6.8, 1.9)
我需要同时通过 x
和 y
对向量 (x, y) 进行插值。通过x
我能做到
approxfun(x, y)(1:7)
但是y
怎么插值呢?我需要在相邻 y1
和 y2
之间获得 n = floor(abs(y1 - y2))
点。
您可以使用 purrr::pmap
结合 dplyr::lag
在 x[i-1]
和 x[i]
之间进行插值。
对于两点之间的线性插值,将间隔削减 x
或 y
并不重要,因此 approxfun(x, y)
仍然有效:
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