[英]2D linear interpolation in R with non-equally spaced values
我有一个关于 R 中非等距值的 2D 插值的问题。我能够使用pracma
包中的interp2()
对等距值进行 2D 线性插值(参见下面的示例)。
等距二维线性插值
library(dplyr)
library(tidyr)
### 2D interpolation with equally-spaced values ###
# Create sample data
data <- expand_grid(val1 = c(seq(1, 5, 1)), val2 = seq(1, 5, 1))
df <- data %>% mutate(z = val1 *val2)
# Transform into matrix
mat <- reshape2::acast(df, val1~val2, value.var="z" )
mat
#> 1 2 3 4 5
#> 1 1 2 3 4 5
#> 2 2 4 6 8 10
#> 3 3 6 9 12 15
#> 4 4 8 12 16 20
#> 5 5 10 15 20 25
# Show plot
lattice::levelplot(mat)
# Create vectors containing coordinates for interpolation
interp_coords <- expand_grid(val1 = seq(1, 5, 0.1), val2 = seq(1, 5, 0.1))
# Interpolate using the interp() from the pracma library
interp_vals <- pracma::interp2(y = c(seq(1, 5, 1)), x = seq(1, 5, 1), Z = mat, xp = interp_coords$val1, yp = interp_coords$val2)
# Bind in new df, convert to matrix and plot
df_2 <- cbind(interp_coords, interp_vals)
mat2 <- reshape2::acast(df_2, val1~val2, value.var="interp_vals" )
lattice::levelplot(mat2)
非等距二维线性插值
接下来,我尝试使用非等距数据集完成相同的操作(见下图; c(seq(1, 5, 1), seq(6, 10, 2)
)。
### 2D interpolation with NON-equally spaced values ###
# Create sample data
df <- expand_grid(val1 = c(seq(1, 5, 1), seq(6, 10, 2)), val2 = seq(1, 5, 1)) %>%
mutate(z = val1 *val2)
# Transform into matrix
mat <- reshape2::acast(df, val1~val2, value.var="z" )
mat
#> 1 2 3 4 5
#> 1 1 2 3 4 5
#> 2 2 4 6 8 10
#> 3 3 6 9 12 15
#> 4 4 8 12 16 20
#> 5 5 10 15 20 25
#> 6 6 12 18 24 30
#> 8 8 16 24 32 40
#> 10 10 20 30 40 50
# Show plot
lattice::levelplot(mat)
显然,插值出了问题,我不明白它是什么。
# Create vectors containing coordinates for interpolation
interp_coords <- expand_grid(val1 = seq(1, 10, 0.1), val2 = seq(1, 5, 0.1))
# Interpolate using the interp() from the pracma library
interp_vals <- pracma::interp2(y = c(seq(1, 5, 1), seq(6, 10, 2)), x = seq(1, 5, 1), Z = mat, xp = interp_coords$val1, yp = interp_coords$val2)
# Bind in new df, convert to matrix and plot
df_2 <- cbind(interp_coords, interp_vals)
mat2 <- reshape2::acast(df_2, val1~val2, value.var="interp_vals" )
lattice::levelplot(mat2)
题
如何在 R 中执行非等距二维线性插值?
由reprex 包(v0.3.0) 于 2020 年 10 月 30 日创建
您只是混淆了interp2
的xp
和yp
参数:
# Create vectors containing coordinates for interpolation
interp_coords <- expand_grid(val1 = seq(1, 10, 0.1), val2 = seq(1, 5, 0.1))
# Interpolate using the interp() from the pracma library
interp_vals <- pracma::interp2(y = c(seq(1, 5, 1), seq(6, 10, 2)),
x = seq(1, 5, 1), Z = mat,
xp = interp_coords$val2,
yp = interp_coords$val1)
# Bind in new df, convert to matrix and plot
df_2 <- cbind(interp_coords, interp_vals)
mat2 <- reshape2::acast(df_2, val1~val2, value.var="interp_vals" )
lattice::levelplot(mat2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.