Search code examples
rleafletgeospatial

Extracting Intersect Values in R


I am wondering if there was a specific way that would allow me to extract the sa3_code_2016 from the QLD sf object and add each corresponding value to the test dataframe.

Solved, needed to assign Points with the same CRS ad QLD and do a st_join()

Example data:

library(absmapsdata)
library(leaflet)
library(tidyverse)


QLD <- sa32016 %>%
  filter(state_name_2016 == "Queensland") %>% 
  dplyr::select(sa3_code_2016,geometry)

Points <- data.frame(Longitude = c(148.275355, 148.872268, 150.490145),
                  Latitude = c(-23.683148, -21.228157,-22.705135),
                  names = c("First", "Second", "Last"))

Points <- st_as_sf(Points, coords = c("Longitude", "Latitude")) %>% 
  st_set_crs(st_crs(QLD))
  
leaflet() %>% 
  addTiles() %>%
  addPolygons(data=QLD, 
              color = "#b3acc2",
              fillOpacity = 0.5) %>%
  addMarkers(data=Points)


library(sf)
Test <- st_join(Points, QLD)

Solution

  • Your error stems form filtering sa32016 but instead of using the filtered data you again use the unfiltered version in your selection process. this leads to your error. by assigning the full data to QLD and then going through the pipe, your process works just fine.

    library(absmapsdata)
    library(leaflet)
    library(tidyverse)
    
    QLD <- sa32016 # note this step
    QLD <- QLD %>%
      filter(state_name_2016 == "Queensland") %>% 
      select(sa3_code_2016,geometry)
    
    name <- c("First", "Second", "Last")
    lat <- c(-23.683148, -21.228157,-22.705135)
    long <- c(148.275355, 148.872268, 150.490145 )
    test <- cbind(name,lat,long)
    
    leaflet() %>% 
      addTiles() %>%
      addPolygons(data=QLD, 
                  color = "#b3acc2",
                  fillOpacity = 0.5) %>%
      addMarkers(data=test,
                 lng = long, 
                 lat = lat)