我有英国的shapefile,但我只想要英格兰和威尔士。这是我到目前为止使用的代码:
RG <- readOGR("filepath", "filename")
UK <- grep("England", "Wales", RG$NAME_1)
RG_EW <- RG[UK]
plot(RG_EW)
但我仍然以整个英国为终结者。我使用从http://www.gadm.org/下载的shapefile
由于
答案 0 :(得分:2)
如果名称是明确的,你只需要选择两个,我只会使用单行而不是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()
答案 1 :(得分:1)
首先,您的grep
来电不正确。如果您正在寻找包含“英格兰”或“威尔士”的字符串,您应该这样做:
UK <- grep("(England|Wales)", RG$NAME_1)
然后您可以使用以下内容对数据进行分组:
RG_EW <- RG[UK,]
你终于得到了:
plot(RG_EW)