[GIS] R filter shapefiles with dplyr

leafletrshapefile

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?)

Best Answer

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.