Subset shapefile

Extract a specific polygon from a shapefile and export it as new shapefile.

Miriam Lerma true
02-04-2023

Intro

Three steps to subset a shapefile and export a new shapefile with the attributes you are interested in.

1. Load shapefile

Load the package sf to load your shapefile into R

Load the package here to use your directory (in which folder is your shapefile)

Load your shapefile, be careful with your directory

Old_shapefile<- read_sf(paste0(My_directory,'/original_shapefile.shp'))

Check the class, theoretically it would show sf

class(Old_shapefile)
[1] "sf"         "tbl_df"     "tbl"        "data.frame"

Explore the contents

str(Old_shapefile)

Check the values in the column that you are interested to subset, to show unique values use the argument unique and to show them in alphabetic order use sort

sort(unique(Old_shapefile$comuna))

2. Filter

Load the package tidyverse

Using the function filter you can subset your old new shapefile and get the new one

In the example we used the column comuna and the value we are interested is La Higuera, do not forget to replace those values

New_shapefile<-Old_shapefile %>%
  filter(comuna=="La Higuera")

3. Export your new shapefile

Check the class of your new object

class(New_shapefile)
[1] "sf"         "tbl_df"     "tbl"        "data.frame"

Export to your selected directory

st_write(New_shapefile, paste0(My_directory,'/New_shapefile.shp'))

Read more