How can I remove some areas by attribute from a shapefile in R and create a new shapefile?

I have been doing this for some time and have made some progress, however, when it comes to overwriting a file, I didn’t have them.

The form file I'm working with is a polygon shape file from the metro and neighborhood, but I'm not interested in neighborhoods, so I work with shp in R to try to remove them from my map.

Data source

To download the file you need, make sure that you select "All states in one national file" in the "Metropolitan / Micropolitan Statistics Area (2010)" section

Here is what I still have:

library(maptools) met=readShapeSpatial("tl_2010_us_cbsa10.shp") met=met@data 

Before a subset:

 NAMELSAD10 LSAD10 Anchorage, AK Metro Area - M1 Clarksdale, MS Micro Area - M2 Richmond, VA Metro Area - M1 Big Spring, TX Micro Area - M2 Dallas-Fort Worth-Arlington, TX Metro Area - M1 Rio Grande City-Roma, TX Micro Area - M2 

then

 submet=subset(met, LSAD10 == "M1") 

After a subset:

 NAMELSAD10 LSAD10 Anchorage, AK Metro Area - M1 Richmond, VA Metro Area - M1 Dallas-Fort Worth-Arlington, TX Metro Area - M1 Vineland-Millville-Bridgeton, NJ Metro Area - M1 Casper, WY Metro Area - M1 Cheyenne, WY Metro Area - M1 

then

 writeSpatialShape(submet, "tl_2010_us_ma10", factor2char = TRUE) 

Using this code, I was able to successfully eliminate the Micropolitan areas designated as "M1", but when I try to overwrite the file, it does not appear in my wd.

I also tried using the "shapefiles" package to do this, but was even less successful. Therefore, any help in this matter would be greatly appreciated.

+4
source share
1 answer

When you execute met=met@data , you lose the spatial aspect of met and just get a plain old data frame.

Then you select this data frame, and then try and writeSpatialShape it. Wow. The submet object has no polygons or coordinates. writeSpatialShape must be barf. But he manages to assimilate it and save it. Check this:

 > writeSpatialShape(1,"foo.shp") > 

and, as you noticed, a shapefile is not created. Wow, this pretty sad error handling.

Two solutions: 1, work on the actual object, and not with the data component, for example:

 met = readOGR(dir,name) submet = met[met$thing=="whatever",] writeOGR(submet,dir,newname,"ESRI Shapefile") 

2, use package:rgdal and read/write|OGR , which not only handles projections, but is also very sick if you try to make it eat something unpleasant:

 > writeOGR(1,".","foo","ESRI Shapefile") Error: inherits(obj, "Spatial") is not TRUE 
+7
source

All Articles