R中具有非等距值的2D线性插值

问题描述

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

等距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,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,0.1),0.1))

# Interpolate using the interp() from the pracma library
interp_vals <- pracma::interp2(y = c(seq(1,x = seq(1,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,value.var="interp_vals" )
lattice::levelplot(mat2)

非等距2D线性插值

接下来,我尝试使用非等距数据集来完成相同的操作(请参见下图; c(seq(1,seq(6,10,2))。

### 2D interpolation with NON-equally spaced values ###
# Create sample data
df <- expand_grid(val1 = c(seq(1,2)),1)) %>% 
  mutate(z = val1 *val2)

# Transform into matrix
mat <- reshape2::acast(df,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,value.var="interp_vals" )
lattice::levelplot(mat2)

问题

如何在R中执行非等距2D线性插值?

reprex package(v0.3.0)于2020-10-30创建

解决方法

您只是混合了xp的{​​{1}}和yp参数:

interp2

enter image description here