I am trying to write a loop where I apply a function to a list of lists. I want to interpolate the temperatures (max mean temperature/MAXMEAN) of different countries with the idw command of the gstat package.
The idw function needs the information of the coordinates (longitude, latitude) and the variable MAXMEAN. These are combined in the data frame list "temperatures.coordinates" (looks like this: https://i.stack.imgur.com/ZNkZp.jpg) which is a list of 37 countries, where each list is seperated again into 12 months (sublist length of 12). The function also needs information from the grd.list dataframe which is a list of length 37 without a sublist.
Applied to a single country and single month, the code looks like this:
# Create a gridded structure
grd <- expand.grid(x = seq(from = x.range[1], to = x.range[2], by = 0.1), y = seq(from = y.range[1], to = y.range[2], by = 0.1))
coordinates(grd) <- ~x + y
gridded(grd) <- TRUE
#Interpolate surface and fix the output. Apply idw model for the data
idw <- idw(formula = MAXMEAN ~ 1, locations = temperatures.coordinates, newdata = grd)
I've tried to do this:
# Create a gridded structure
grd <- list()
for (i in 1:length(countrybounds)) {
grd[[i]] <- expand.grid(x = seq(from = (x.range[[i]])[1], to = (x.range[[i]])[2], by = 0.1), y = seq(from = (y.range[[i]])[1], to = (y.range[[i]])[2], by = 0.1))
coordinates(grd[[i]]) <- ~x + y
gridded(grd[[i]]) <- TRUE
grd.list <- grd
gridded(grd.list[[i]]) <- TRUE
}
#Interpolate surface and fix the output. Apply idw model for the data
idw.list <- list()
for (i in 1:length(grd.list)) {
idw.list[[i]] <- list()
for (j in 1:length(grd[[i]])) {
idw.list[[i]][[j]] <- idw(formula = MAXMEAN ~ 1, locations = (temperatures.coordinates[[i]][[j]]), newdata = grd.list[[i]])
}
}
I receive this error after running the loop:
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘idw’ for signature ‘"formula", "data.frame"’
This has worked in a similar previous loop, where I create the list of lists for the temperature coordinates:
temperatures.coordinates <- list()
for(i in 1:length(monthlymean)){
temperatures.coordinates[[i]] <- list()
for(j in 1:length(monthlymean[[i]])){
temperatures.coordinates[[i]][[j]]<-(monthlymean[[i]][[j]])[,c("LON","LAT","MAXMEAN")]
}
}
I'm not sure if I gave all the relevant info and I've been stuck on this for a while - appreciate any help, thanks!