R中具有非等间距值的二维线性插值

2D linear interpolation in R with non-equally spaced values

我有一个关于 R 中非等距值的二维插值的问题。我能够使用 pracma 包中的 interp2() 对等距值进行二维线性插值(参见下面的示例)。

等距二维线性插值

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 package (v0.3.0)

于 2020-10-30 创建

您只是混淆了 interp2:

xpyp 参数
# 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)