Reputation: 1
I have a shapefile for the UK but I only want England and Wales. Here is the code I've used so far:
RG <- readOGR("filepath", "filename")
UK <- grep("England", "Wales", RG$NAME_1)
RG_EW <- RG[UK]
plot(RG_EW)
But I still end up with the whole of the UK. I'm using a shapefile downloaded from http://www.gadm.org/
Thanks
Upvotes: 0
Views: 1091
Reputation: 7997
If the names are unambiguous and you only need to select two, I would just use a one-liner rather than use grep
:
e.w.shp <- uk.shp[uk.shp$NAME_1 == "England" | uk.shp$NAME_1 == "Wales", ]
And the result looks like this:
> str(e.w.shp)
Formal class 'SpatialPolygonsDataFrame' [package "sp"] with 5 slots
..@ data :'data.frame': 134 obs. of 11 variables:
.. ..$ ID_0 : int [1:134] 239 239 239 239 239 239 239 239 239 239 ...
.. ..$ ISO : chr [1:134] "GBR" "GBR" "GBR" "GBR" ...
.. ..$ NAME_0 : chr [1:134] "United Kingdom" "United Kingdom" "United Kingdom" "United Kingdom" ...
.. ..$ ID_1 : int [1:134] 1 1 1 1 1 1 1 1 1 1 ...
.. ..$ NAME_1 : chr [1:134] "England" "England" "England" "England" ...
.. ..$ ID_2 : int [1:134] 1 2 3 4 5 6 7 8 9 10 ...
.. ..$ NAME_2 : chr [1:134] "Barking and Dagenham" "Bath and North East Somerset" "Bedfordshire" "Berkshire" ...
.. ..$ NL_NAME_2: chr [1:134] NA NA NA NA ...
.. ..$ VARNAME_2: chr [1:134] NA NA NA NA ...
.. ..$ TYPE_2 : chr [1:134] "London Borough" "Unitary Authority" "Administrative County" "County" ...
.. ..$ ENGTYPE_2: chr [1:134] "London Borough" "Unitary Authority" "Administrative County" "County" ...
..@ polygons :List of 134
So a fully worked example using ggplot2
rather than base graphics might go something like this:
library(rgdal)
library(ggplot2)
library(rgeos)
shape.dir <- "your_directory_name" # use your directory name here
uk.shp <- readOGR(shape.dir, layer = "GBR_adm2")
e.w.shp <- uk.shp[uk.shp$NAME_1 == "England" | uk.shp$NAME_1 == "Wales", ]
e.w.df <- fortify(e.w.shp, region = "ID_2") # convert to data frame for ggplot
ggplot(e.w.df, aes(x = long, y = lat, group = group)) +
geom_polygon(colour = "black", fill = "grey80", size = 0.5) +
theme()
Upvotes: 2
Reputation: 49033
First, your grep
call is incorrect. If you are looking for strings containing either "England" or "Wales" you should do :
UK <- grep("(England|Wales)", RG$NAME_1)
And then you can subset your data with :
RG_EW <- RG[UK,]
And you finally get :
plot(RG_EW)
Upvotes: 1