Since it is not appreciated to ask a question under an already existing question which has been answered, here my question linking to this question URL:Simple way to subset SpatialPolygonsDataFrame (i.e. delete polygons) by attribute in R where you can also acquire the dataset.
Does anyone have an idea how to remove multiple features from the SpatialPolygonsDataFrame based on a vector of values?
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
I would like to remove the features which have the NAMES 'Finland', 'Norway', 'Sweden', 'Denmark' (no offense, I just do not have data for Scandinavia ;) ).
Following approaches failed:
world.map <- world.map[world.map@data$NAME != c('Finland', 'Norway', 'Sweden', 'Denmark'), ]
# does not work at all
world.map <- dplyr::filter(world.map@data, NAMEN %in% c('Finland', 'Norway', 'Sweden', 'Denmark'))
# results in a dataframe, spatial information is lost
I would guess that there is an approach using base::which()
and %in%
, but I do not have any idea how to go on. The answer of @Jeffrey Evans in this post see URL:https://gis.stackexchange.com/questions/57844/subset-a-spatialpolygonsdataframe-by-id-in-r could provide a useful hint...
You may subset the SpatialPolygonsDataFrame
by row ids:
# row numbers of countries, exluding scandinavia
ids <- which(
!(world.map$NAME %in% c('Finland', 'Norway', 'Sweden', 'Denmark'))
)
# subset
not_scandinavia <- world.map[ids, ]
# plot
plot(not_scandinavia)