Iterate over multiple dependent variables (columns) of an sp dataframe when using krige.cv

143 views Asked by At

I have a SpatialPointsDataframe called rain and I would like to fit a variogram and perfom cross-validation for each one of its last 10 columns (dependent variables) like below:

  fit.reg.vgm <- autofitVariogram(
  column (dependent variable) ~ X + Y + Z + AS + SL,
  rain,
  model = c("Sph", "Exp", "Gau", "Lin", "Log"),
  fix.values = c(NA, NA, NA),
  verbose = FALSE,
  GLS.model = NA,
  start_vals = c(NA, NA, NA),
  miscFitOptions = list()
)
  cv <-krige.cv(column (dependent variable) ~ X + Y + Z + AS + SL, rain, fit.reg.vgm$var_model)

Does anyone know how to construct such a for-loop?

Thanks in advance!

2

There are 2 answers

0
Roman Luštrik On BEST ANSWER

You will need to construct a formula. Try formula() and paste(). Something along the lines of

x <- c("a", "b", "c")
out <- list()

for (i in seq_along(x)) {
  out[[i]] <- formula(paste(x[i], "~ X + Y + Z"))
}


> out
[[1]]
a ~ X + Y + Z

[[2]]
b ~ X + Y + Z

[[3]]
c ~ X + Y + Z
0
akrun On

An option with reformulate

out <- vector('list', length(x))
for(i in seq_along(x)) {out[[i]] <- reformulate(c("X", "Y", "Z"), response = x[i]) }
out
#[[1]]
#a ~ X + Y + Z

#[[2]]
#b ~ X + Y + Z

#[[3]]
#c ~ X + Y + Z