1

I am trying to create an R function that would run a GWR on variables that the user specifies from a Spatial Polygons Data Frame. The end result of running the function are two mappings - one of the independent variable's values and one of the coefficient values from the GWR model. I'm having trouble with the second map.

I have managed to create the GWR model and a 'results' object for the coefficients that I would be visualizing.

  gwr.model <- gwr(SpatialPolygonsDataFrame@data[, y] ~ SpatialPolygonsDataFrame@data[, x], 
                   data = SpatialPolygonsDataFrame, 
                   adapt = GWRbandwidth, 
                   hatmatrix = TRUE, 
                   se.fit = TRUE)    
  results <- as.data.frame(gwr.model$SDF)
  gwr.map <- SpatialPolygonsDataFrame
  gwr.map@data <- cbind(SpatialPolygonsDataFrame@data, as.matrix(results))

To create the visualization of the GWR coefficients, I have to specify my tm_fill() to be a column from the 'results' object, but I do not know how to do it so that the function may be used will any Spatial Polygons Data Frame. So far, I have tried using the paste0() function, as so:

map2 <- tm_shape(gwr.map) + tm_fill(paste0("SpatialPolygonsDataFrame.", x), n = 5, style = "quantile", title = "Coefficient") +
        tm_layout(frame = FALSE, legend.text.size = 0.5, legend.title.size = 0.6)

But I got an error saying that the fill argument is neither colors nor a valid variable name.

I'll be grateful for any tips that could help me resolve the issue.

1 Answers1

0

Switching to the package sf - leaving sp behind - probably will solve your problem here.

In the absence of a reproducible example, let me try to suggest the following here: convert your results with gwr.map.sf <- sf::st_as_sf(gwr.map). Then you add the results of your GWR simply as a new column: gwr.map$results <- results (my understanding is that the dimensions should fit).

Finally you should be able to plot like this:

map2 <- tm_shape(gwr.map.sf) + tm_fill("results", n = 5, style = "quantile", title = "Coefficient") +
        tm_layout(frame = FALSE, legend.text.size = 0.5, legend.title.size = 0.6)