首页 > 解决方案 > R中具有非等间距值的二维线性插值

问题描述

我有一个关于 R 中非等间距值的 2D 插值的问题。我能够使用interp2()来自pracma包的等间距值进行 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 包于 2020-10-30 创建(v0.3.0)

标签: rinterpolationlinear-interpolation

解决方案


您只是混淆了 的xpyp参数interp2

# 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)

在此处输入图像描述


推荐阅读