7

How to filter shapefiles data in R with dplyr and then put it in a leaflet map?

not reproducible example sorry:

library(dplyr)
library(leaflet)
library(sp)
library(maptools)
library(rgdal)

lines<- readShapeLines("test",verbose=TRUE, proj4string=XXX)
lines@data<-lines@data %>%
  filter(X>400,Y=="YES") 

m = leaflet() %>% addTiles()
m %>%addPolylines(data=lines,col="blue")

I woulk like to make a leaflet map only with the data selected (attribute X>400 and attribute Y =="YES") ,

"addPolylines(data=lines)" add all lines in the shapefiles

(do I need to merge lines@data with lines?)

3
  • Could you please supply more details on what you are trying to do (e.g. how do you want to filter your shapefile?) and what your script is doing?
    – Aaron
    Jul 29, 2015 at 11:08
  • 1
    You have to use the subset method (see ?subset.Spatial): subset(lines, X > 400 & Y=="YES"); or use indexing via []. Your example filters just the data frame and not the lines.
    – rcs
    Jul 29, 2015 at 11:27
  • @Aaron The data of my shapefile contain two attributes X and Y that I would like to filter with dplyr and then create a leaflet map of the results.
    – Felipe
    Jul 29, 2015 at 11:31

2 Answers 2

15

You have to use the subset method (see ?subset.Spatial):

 subset(lines, X > 400 & Y=="YES")

Alternatively you can use indexing operations via []:

 lines[lines$X > 400 & lines$Y=="YES", ]

Your dplyr code just filters the data frame, but not the geometry.

9

Since this is one of the first links that appear when you search how to filter a spatial file with dplyr I think an update is due. You now could simply transform your shapefile to an SF object and filter with dplyr like verbs. You could try something like this:

lines <- st_as_sf(lines)
lines <- lines %>%
    dplyr::filter(X>400 & Y=="YES")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.