I am currently struggling with spatial dataframes using leaflet to create interactive maps. in R I have been trying out many different solutions from multiple threads, but my addPolygon() does not seem to work at all. Can anyone help me trying to figure out what goes wrong? I have replicated my dataset in a simple format (def_rep) and the spatial data is on the state level for which I call tigris::states(). I then merge the dataframes into merged_df_rep and continue with setting up the leaflet(). But I always get the same error: Error in UseMethod("metaData") : no applicable method for 'metaData' applied to an object of class "c('sfc_MULTIPOLYGON', 'sfc')". Many thanks for any help or pointers as to what I am doing wrong!
Here is my code and an example df:
library(ggmap)
library(tidygeocoder)
library(tigris)
library(sf)
library(htmltools)
library(labelled)
library(leaflet)
library(tidyverse)
NAME <- c("West Virginia", "Florida", "Illinois", "Minnesota","Maryland", "Rhode Island", "Idaho", "New Hampshire","North Carolina", "Vermont", "Connecticut", "Delaware","New Mexico", "California", "New Jersey", "Wisconsin", "Oregon", "Nebraska","Pennsylvania","Washington", "Louisiana", "Georgia", "Alabama" , "Utah","Ohio","Texas", "Colorado", "South Carolina","Oklahoma" , "Tennessee", "Wyoming", "Hawaii", "North Dakota", "Kentucky", "Maine" , "New York", "Nevada" , "Alaska" , "Michigan", "Arkansas","Mississippi","Missouri", "Montana" ,"Kansas", "Indiana", "South Dakota","Massachusetts", "Virginia", "District of Columbia", "Iowa","Arizona")
values <- c(1000:1050)
df_rep <- data.frame(NAME, values)
map_df <- states()
problems <- anti_join(map_df,df_rep, by = "NAME")
head(problems[,1:7])
###dropping the problems
map_df_clean<-map_df[!(map_df$NAME=="United States Virgin Islands" | map_df$NAME=="Commonwealth of the Northern Mariana Islands"| map_df$NAME=="Guam"| map_df$NAME=="Puerto Rico"| map_df$NAME=="American Samoa"),]
merged_df_rep <- left_join(map_df_clean, df_rep, by = "NAME")
##try to transform the data
merged_df_rep <- st_transform(merged_df_rep, "+proj=longlat +datum=WGS84")
pal <- colorNumeric("Greens", domain = merged_df_rep$values) ##create a color palette
#states_merged_df <- sf::as_Spatial(states_merged_df)
popup_sb <- paste0("Total values for" ,merged_df_rep$NAME, "Number:", as.character(merged_df_rep$values)) ##create the correct popup
merged_df_rep %>%
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
setView(~-98.483330,38, .712046, zoom = 4) %>%
addPolygons(
data = merged_df_rep$geometry,
fillColor = ~pal(merged_df_us_1$n_response),
fillOpacity = .7,
weight = .2,
smoothFactor = .2,
popup = ~popup_sb) %>%
addLegend(pal = pal,
values = merged_df_rep$values,
position = "bottomright",
title = "Responses")