title: Using data from 2 shapefiles with leaflet in R
body: <p>Problem: We have an area divided into regions, which are further divided into subregions.</p>
  
  <p>Our Task : Create a map of the area, such that when we hover over a point,it should highight the boundary of the region and the tooltip should show the name of the subregion and region.</p>
  
  <p>Solution 1 : Create a shapefile of the regions. Now when we hover over a point it will highlight the boundary of the region but the tooltip will not show the name of the corresponding subregion,it will show the name only of the region.</p>
  
  <p>This is how I can do it with leaflet in R:</p>
  
  <pre><code>library(tigris)
  library(dplyr)
  library(leaflet)
  
  m1 &lt;- states()
  m2 &lt;- counties()
  
  head(m1@data)
  head(m2@data)
  
  #Map 1
  
  labels &lt;- sprintf("State name : %s",
  m1@data$NAME) %&gt;% lapply(htmltools::HTML)
  
  leaflet(data = m1) %&gt;%
  addPolygons(
  highlight = highlightOptions(
  weight = 5,
  color = "#666",
  dashArray = "",
  fillOpacity = 0.7,
  bringToFront = TRUE),
  label = labels)
  </code></pre>
  
  <p>Solution 2 : Create a shapefile of the subregions. Now when we hover over a point it will highlight the boundary of the subregion and NOT the boundary of the region, but it will show the name of the corresponding region and subregion.</p>
  
  <p>This is how I can do it with leaflet in R:</p>
  
  <pre><code>#Map 2
  
  # Keep statefp and the name of the State.
  m3 &lt;- m1@data[,c(3,7)]
  
  names(m3)[2] &lt;- "StateName"
  
  m2@data &lt;- left_join(m2@data,m3,by = c("STATEFP"))
  
  labels &lt;- sprintf("State name : %s&lt;br&gt;County Name : %s",
  m2@data$StateName,m2@data$NAME) %&gt;% lapply(htmltools::HTML)
  
  
  leaflet(data = m2) %&gt;%
  addPolygons(
  highlight = highlightOptions(
  weight = 5,
  color = "#666",
  dashArray = "",
  fillOpacity = 0.7,
  bringToFront = TRUE),
  label = labels)
  </code></pre>
  
  <p>Query : How can we mix 1 and 2 ? how can we display the boundary of the region but the name of the subregion (and region) when we hover over a point ? </p>
  
  <p>Thanks to Michael Bird for recommending to use tigris.</p>