R

时间:2016-08-07 14:31:36

标签: r interpolation gstat

我想使用来自idw包的gstat命令使用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循环,但它不起作用。

EDIT 不起作用的代码是:

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

1 个答案:

答案 0 :(得分: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 = "\\_")

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