Skip to content

Instantly share code, notes, and snippets.

@boshek
Created September 19, 2018 21:23
Show Gist options
  • Save boshek/c5b79fe3765539225a4c9b179886776a to your computer and use it in GitHub Desktop.
Save boshek/c5b79fe3765539225a4c9b179886776a to your computer and use it in GitHub Desktop.
Calculate Area with sf

Calculate Area with sf

library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

nc <- read_sf(system.file("shape/nc.shp", package="sf"))


## Two ways
## By group
nc %>% 
  mutate(grouping_var = "full_basin") %>% 
  group_by(grouping_var) %>% 
  summarise() %>% 
  mutate(full_area = st_area(geometry))
#> Simple feature collection with 1 feature and 2 fields
#> geometry type:  MULTIPOLYGON
#> dimension:      XY
#> bbox:           xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> epsg (SRID):    4267
#> proj4string:    +proj=longlat +datum=NAD27 +no_defs
#> # A tibble: 1 x 3
#>   grouping_var full_area                                          geometry
#>   <chr>        <S3: units>                             <MULTIPOLYGON [°]>
#> 1 full_basin   127031757146~ (((-76.54427 34.58783, -76.55515 34.61066, -~

## Or just figure out the area of each polygon then sum it up
nc_area <- nc %>% 
  mutate(individual_area = st_area(geometry)) 

sum(nc_area$individual_area)
#> 127031757146 m^2

Created on 2018-09-19 by the reprex package (v0.2.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment