I have a SpatialLinesDataFrame in R that is a road network dataset. The names of certain roads begin with the string "NH" to indicate that these are national highways. E.g., NH44, NH75 etc. Roads that are not national highways have names beginning with other strings.

I want to subset the roads dataset to include just roads that are national highways. Is there any way to do this in R?


Assuming your name is in a column called name and your spatial lines object is called d, you can do the same as with any data frame in R, and select rows by some logical operation. Here I use grepl to match a string starting NH:

> d = data.frame(name=c("M1","NH2","Not NH","NH3","NHx"),z=1:5)
> d[which(grepl("^NH",d$name)),]
  name z
2  NH2 2
4  NH3 4
5  NHx 5

Note my test cases includes something with NH not at the start.

  • Thanks! This works – Arpit Aug 7 '19 at 5:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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