通过R中的属性对SpatialPolygonsDataFrame(即删除多边形)进行子集化的简单方法 [英] Simple way to subset SpatialPolygonsDataFrame (i.e. delete polygons) by attribute in R
问题描述
我只想基于@data数据框中的相应属性值从SpatialPolygonsDataFrame对象中删除一些多边形,以便可以绘制简化/子集的shapefile.到目前为止,我还没有找到一种方法.
I would like simply delete some polygons from a SpatialPolygonsDataFrame object based on corresponding attribute values in the @data data frame so that I can plot a simplified/subsetted shapefile. So far I haven't found a way to do this.
例如,假设我要从此世界形状文件中删除所有多边形面积小于30000.我该怎么做?
For example, let's say I want to delete all polygons from this world shapefile that have an area of less than 30000. How would I go about doing this?
或者类似地,如何删除南极洲?
Or, similarly, how can I delete Antartica?
require(maptools)
getinfo.shape("TM_WORLD_BORDERS_SIMPL-0.3.shp")
# Shapefile type: Polygon, (5), # of Shapes: 246
world.map <- readShapeSpatial("TM_WORLD_BORDERS_SIMPL-0.3.shp")
class(world.map)
# [1] "SpatialPolygonsDataFrame"
# attr(,"package")
# [1] "sp"
head(world.map@data)
# FIPS ISO2 ISO3 UN NAME AREA POP2005 REGION SUBREGION LON LAT
# 0 AC AG ATG 28 Antigua and Barbuda 44 83039 19 29 -61.783 17.078
# 1 AG DZ DZA 12 Algeria 238174 32854159 2 15 2.632 28.163
# 2 AJ AZ AZE 31 Azerbaijan 8260 8352021 142 145 47.395 40.430
# 3 AL AL ALB 8 Albania 2740 3153731 150 39 20.068 41.143
# 4 AM AM ARM 51 Armenia 2820 3017661 142 145 44.563 40.534
# 5 AO AO AGO 24 Angola 124670 16095214 2 17 17.544 -12.296
如果我做这样的事情,那么情节不会反映出任何变化.
If I do something like this, the plot does not reflect any changes.
world.map@data = world.map@data[world.map@data$AREA > 30000,]
plot(world.map)
如果执行此操作,结果相同:
same result if I do this:
world.map@data = world.map@data[world.map@data$NAME != "Antarctica",]
plot(world.map)
感谢您的帮助!
推荐答案
似乎正在覆盖数据,但未删除多边形.如果您想缩减同时包含数据和多边形的数据集,请尝试例如
looks like you're overwriting the data, but not removing the polygons. If you want to cut down the dataset including both data and polygons, try e.g.
world.map <- world.map[world.map$AREA > 30000,]
plot(world.map)
[]
该解决方案曾经可以使用,但@Bonnie会报告较新的R版本(尽管也许数据也已更改?):
world.map <- world.map[world.map@data$AREA > 30000, ]
如果有帮助,请支持@Bonnie的答案.
[]
That solution used to work, but @Bonnie reports otherwise for a newer R version (though perhaps the data has changed too?):
world.map <- world.map[world.map@data$AREA > 30000, ]
Upvote @Bonnie's answer if that helped.
这篇关于通过R中的属性对SpatialPolygonsDataFrame(即删除多边形)进行子集化的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!