我有一个英国的 shapefile,但我只想要英格兰和威尔士。这是我到目前为止使用的代码:
RG <- readOGR("filepath", "filename")
UK <- grep("England", "Wales", RG$NAME_1)
RG_EW <- RG[UK]
plot(RG_EW)
但我最终还是选择了整个英国。我正在使用从http://www.gadm.org/下载的 shapefile
谢谢
我有一个英国的 shapefile,但我只想要英格兰和威尔士。这是我到目前为止使用的代码:
RG <- readOGR("filepath", "filename")
UK <- grep("England", "Wales", RG$NAME_1)
RG_EW <- RG[UK]
plot(RG_EW)
但我最终还是选择了整个英国。我正在使用从http://www.gadm.org/下载的 shapefile
谢谢
如果名称是明确的并且您只需要选择两个,我将只使用单行而不是使用grep
:
e.w.shp <- uk.shp[uk.shp$NAME_1 == "England" | uk.shp$NAME_1 == "Wales", ]
结果如下所示:
> 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
因此,使用而不是基本图形的完整示例ggplot2
可能会是这样的:
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()
首先,你的grep
电话不正确。如果您正在寻找包含“England”或“Wales”的字符串,您应该这样做:
UK <- grep("(England|Wales)", RG$NAME_1)
然后您可以使用以下方法对数据进行子集化:
RG_EW <- RG[UK,]
你终于得到:
plot(RG_EW)