15

I'm working with shapefile in R and I need to calculate the polygons' area that I created by Gdiference function, So ,now I need to create a column with the size of freshly polygons created, because after that I need take out the small polygons which are not important to my academic research

I didn't use any function yet.

1
  • Take a look at ?rgeos::gArea Commented Jun 27, 2018 at 1:20

2 Answers 2

28

Can you provide data for an example? Anyways, try this:

library(sf)
f <- st_read("shapefile.shp")
f$area <- st_area(f) #Take care of units

Best

2
  • It worked, but when I tried to use the shapefile function, returns me a error. Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘shapefile’ for signature ‘"sf"’ Commented Jun 27, 2018 at 1:43
  • 1
    The raster::shapefile function is for reading data from on-disk files and returns a polygon object using the sp package's methods for representing spatial data in R (in this case, a SpatialPolygonsDataFrame). If you want to convert the sf polygon dataframe back to an SPDF, use as(f, 'Spatial'). To go from sp to sf, you can use sf::st_as_sf(f). If all you want to do is write your result back to disk, you don't have to convert to sp first - just use sf::st_write().
    – obrl_soil
    Commented Jun 27, 2018 at 3:24
6

Use sf::st_area

Pro tip: dplyr::mutate allows you to do multiple computations at once. For example, if your shapefile units are in meters, you can easily compute the area in acres or hectares as well.

library(sf); library(tidyverse)
p <- st_read("polygon.shp")


p %>% 
  dplyr::mutate(area_meters = st_area(p),
                # 1 m2 = 0.0.000247105 acres
                area_acres = area_meters * 0.0.000247105,
                # 1m2 = 0.0001 hectares
                area_hectares = area_meters * 0.0001)
1
  • 10
    The result of sf::st_area is a unit class object so, you can simply use units::set_units to change the unit to something else eg., set_units(st_area(p), "acre") and not have to remember conversion factors. Commented Nov 10, 2022 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.