R中的IDW参数

IDW parameters in R

我想使用 gstat 包中的 idw 命令使用 R 执行 IDW 插值。我有这个数据:

#settings
library(gstat)
library(dplyr)
library(sp)
library(tidyr)

id_rep <- rep(c(1,2), 20)
f <- rep(c(930,930.2), each=20)
perc <- rep(c(90, 80), each=10)
x <- sample(1:50, 40)
y <- sample(50:100, 40)
E <- runif(40)
df <- data.frame(id_rep, perc, x,y, f, E)
df_split <- split(df, list(df$id_rep, df$perc, df$f), drop = TRUE, sep="_")

#grid
x.range <- range(df$x)
y.range <- range(df$y)

grid <- expand.grid(x = seq(x.range[1], x.range[2], by=1), 
                       y = seq(y.range[1], y.range[2], by=1))
coordinates(grid) <- ~x + y

#interpolation
lst_interp_idw <- lapply(df_split, function(X) {

   coordinates(X) <- ~x + y
    E_idw <- idw(E~ 1, X, grid, idp=1, nmax=3) %>% as.data.frame()

   df_interp <- select(E_idw, x,y,E_pred=var1.pred)
   df_interp
})

  df_interp_idw <- bind_rows(lst_interp_idw, .id = "interact") %>%
  separate(interact, c("id_rep", "perc", "f"), sep = "\_")

现在我想在特定值内用不同的idpnmax参数执行每个运行(idp从1到3乘以0.5,nmax从3到6乘以1 ) 并为 idp 和 nmax 值的每个组合得到一个包含列的数据框。我尝试使用两个 for 循环,但它不起作用。

编辑 无效的代码是:

idp = seq(from = 1, to = 3, by = 0.5)
nmax = seq(from = 3, to = 6, by = 1)

...
for(i in idp) {
  for(j in nmax)
{ E_idw= idw(E ~ 1, X, grid, nmax = i, idp = j)
  }
} 
...

这是一种将每次迭代的结果存储在列表中的方法。

#settings
#install.packages("gstat")
library(gstat)
library(dplyr)
library(sp)
library(tidyr)

id_rep <- rep(c(1,2), 20)
f <- rep(c(930,930.2), each=20)
perc <- rep(c(90, 80), each=10)
x <- sample(1:50, 40)
y <- sample(50:100, 40)
E <- runif(40)
df <- data.frame(id_rep, perc, x,y, f, E)
df_split <- split(df, list(df$id_rep, df$perc, df$f), drop = TRUE, sep="_")

#grid
x.range <- range(df$x)
y.range <- range(df$y)

grid <- expand.grid(x = seq(x.range[1], x.range[2], by=1), 
                    y = seq(y.range[1], y.range[2], by=1))
coordinates(grid) <- ~x + y

# ==============================================
# NEW function
# ==============================================

idp = seq(from = 1, to = 3, by = 0.5)
nmax = seq(from = 3, to = 6, by = 1)

#interpolation
lst_interp_idw <- lapply(df_split, function(X) {

  coordinates(X) <- ~x + y

  df_interp <- vector(length(idp)*length(nmax), mode = "list" )

  k <- 0

  for(i in idp) {

    for(j in nmax) {

      print(paste(i, j))

      # Iterator
      k <- k + 1

      E_idw= idw(E ~ 1, X, grid, nmax = i, idp = j) %>% as.data.frame()

      df_interp[[k]] <- select(E_idw, x,y,E_pred=var1.pred)

    }
  }

  return(df_interp)
})

# ==============================================

一些合理性检查(lapply 应用于 8 个列表元素并计算了 20 个变化):

length(lst_interp_idw) # 8
length(lst_interp_idw[[1]]) #20
length(lst_interp_idw[[1]]) #20

您应该很容易调整代码的最后一行

df_interp_idw <- bind_rows(lst_interp_idw, .id = "interact") %>%
  separate(interact, c("id_rep", "perc", "f"), sep = "\_")

以所需格式格式化输出。这在很大程度上取决于您希望如何呈现不同的插值替代方案。