Adding Regression Results to a Map / Shapefile

Hi!

I’ve been working in a dashboard to predict covid19 rate across Texas counties. I would like to display on a map the predicted results of a linear regression model. However, I don’t know how to add the predicted results to the shapefile so I can select the column and display it on the map.

First, I am starting by importing the data and map so I can run the regression analysis.

data <- read.csv("E:\\Tec21\\AD3003B\\texas_counties_data_alt2.csv", col.names = c("county","geocode", "median.household.income", "poverty", "pop.density", "adult.obesity", "covid.2021"))

variables <- c("median.household.income", "poverty", "pop.density", "adult.obesity")

map <- readOGR(dsn = "E:\\Tec21\\IA - Etapa 1\\Texas_Counties\\County.shp")

Then, I run the regression analysis according to the user selection of explanatory variables.

selectInput("variable_choice", label = h5("Choose one or more input variables"), choices = variables, variables[1], multiple = TRUE)
model1 <- reactive({
vars <- as.matrix(data[, input$variable_choice])
lm(covid.2021 ~ vars, data=data)
})

Then, I add the predicted values to a new dataset and display the summary

d_predicted <- reactive({
d_predicted <- data %>% mutate(predicted=predict(model1()), geocode=data$geocode, county=data$county)
})
renderPrint({
summary(d_predicted())
})

However, when trying to add the predicted values to the map (shapefile) I got an error: ‘’ object of type 'closure' is not subsettable”

renderLeaflet({
map@data$predicted <- d_predicted$predicted
})

I can plot the map, but I can not add the predicted values.

```{r}
renderLeaflet({
  pal <- colorNumeric("YlOrRd", map$predicted)
  leaflet() %>%
  addTiles() %>%
  addPolygons(data = map,
              fillColor = ~pal(predicted), 
              fillOpacity = 1, 
              weight = 1)
})

I would really appreciate your help!

Thanks!

From the way you access the map@data slot in your code I get the impression you are working within framework of older sp package; your use of rgdal::readOGR() is another hint that your workflow is by now somewhat dated - you did notice the warning at the package startup, did you?

I suggest you update to newer sf paradigm; you will notice that the sf objects are regular data frames (plus some little extra special sauce), and creating new variables will feel like breeze compared to sp.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.