2
votes

I have an sf table where I need to extract one of the polygons, clip it to a bounding box, and then write it back to the sf so I can plot the original with the one revised polygon. I've figured out how to do everything but write the revised polygon back to original sf.

Here is a reproducible example using the NC dataset from the sf package. Where I county_clipped back into the nc dataset I get an error. What do I need to do here?

#Read NC shape from sf package
nc <- st_read(system.file("shape/nc.shp", package="sf"))

#extract county of interest
county <-nc[[1,"geometry"]]

#construct polygon to be clipped
bboxpolygon = st_polygon(list(rbind(c(-81.65,36.23), 
                                     c(-81.65,36.45), 
                                     c(-81.23,36.45), 
                                     c(-81.23,36.23), 
                                     c(-81.65,36.23))))
#Plot bounding box and county
par(mar = c(0,0,1,0))
plot(county)
plot(bboxpolygon, add=TRUE)   

#clip county
county_clipped <-st_intersection(county,bboxpolygon)

#confirm clipping worked
plot(county_clipped)

#write revised polygon back to dataset
nc[1,"geometry"]<-county_clipped

#plot revised object
plot(nc$geometry)
1
I think it needs to be made into an sfc object nc[1,"geometry"] <- sf::st_sfc( county_clipped )SymbolixAU
Remember, also, the AREA, PERIMETER, and other attributes will be incorrect for this new shapeSymbolixAU

1 Answers

3
votes

The geometry column in an sf object is an sfc object, which is a collection of sfg objects.

attr( nc, "class" )
# [1] "sf"         "data.frame"

attr( nc$geometry, "class" )
# [1] "sfc_MULTIPOLYGON" "sfc"

Your county_clipped object is sfg

attr( county_clipped, "class" )
# [1] "XY"      "POLYGON" "sfg"

So in order for you to update a 'geometry', it needs to be an sfc object

nc[1,"geometry"] <- sf::st_sfc( county_clipped )

Noting the AREA, PERIMETER, and other attributes will be incorrect for this new shape