I have a polygon shapefile in R and would like to create a new column with each polygon's areas and perimeters. I have the following code which successfully generates areas, but not perimeters:
data<-arc.select(data.path) %>%
arc.data2sf() %>% #convert data to SF object
mutate(District=sub("^0 ", "",SLDUST20)) #remove leading 0s to district column
data$Shape_Area=st_area(data) #calculate district areas
data$Shape_length=lwgeom::st_perimeter(data) #calculate district perimeters
This yields the following error message: Error in lwgeom::st_perimeter(SD_senate) : for perimeter of longlat geometry, cast to LINESTRING and use st_length
CodePudding user response:
Set up data:
> library(sf)
> example(st_read) # get the `nc` object
Replicate your error:
> st_perimeter(nc)
Error in st_perimeter(nc) :
for perimeter of longlat geometry, cast to LINESTRING and use st_length
Try suggestion:
> st_length(st_cast(nc,"LINESTRING"))
Error in st_cast.sfc(st_geometry(x), to, group_or_split = do_split) :
use smaller steps for st_cast; first cast to MULTILINESTRING or POLYGON?
Try suggestion suggested by the suggestion:
> st_length(st_cast(nc,"MULTILINESTRING"))
Units: [m]
[1] 141627.32 119875.85 160458.17 301643.62 211793.62 160780.01 150430.19
[8] 123169.65 141072.70 140583.19 134369.71 157789.72 170610.20 132133.88
[15] 112628.81 216204.53 116256.22 194694.89 124620.43 99987.87 116904.13
Note that even though the object is in lat-long coordinates you get perimeters in meters.