0

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

#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)
  }
} 
...
4

1 回答 1

0

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

#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 = "\\_")

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

于 2016-08-07T22:16:44.113 回答