Change shapefile to Data frame based on Latitude and Longitude values in R

122 Views Asked by At

I want to change my shapefile (.sh) to dataframe in R based on Lat and Lon values. Below is the structure of my shapefile

GID    NPP      SPEED        density            centroid
25   226.5086 0.01680688 0.007315422 POINT (607.5326 6098.749)
26   240.5463 0.02550360 0.008853372 POINT (614.5326 6098.749)
27   237.2356 0.02817464 0.019529638 POINT (621.5326 6098.749)
28   201.2196 0.02344988 0.008542002 POINT (628.5326 6098.749)
29   174.6828 0.01887059 0.008363818 POINT (635.5326 6098.749)
30   160.6849 0.01619619 0.002521799 POINT (642.5326 6098.749)

The Latitude and Longitude values are the centroid values. I want my dataframe to look like below.

GID      NPP      SPEED     density      Lat      Lon
25   226.5086 0.01680688 0.007315422  607.5326 6098.749
26   240.5463 0.02550360 0.008853372  614.5326 6098.749
27   237.2356 0.02817464 0.019529638  621.5326 6098.749
28   201.2196 0.02344988 0.008542002  628.5326 6098.749
29   174.6828 0.01887059 0.008363818  35.5326  6098.749
30   160.6849 0.01619619 0.002521799  642.5326 6098.749
1

There are 1 best solutions below

0
TarJae On BEST ANSWER

We can do it witht the sf package: Note to use geometry.

library(sf)

# your shapefile
shapefile <- st_read("my_shapefile.shp")

# get the coordinates
centroid <- st_coordinates(shapefile$geometry)

# create the data frame
data.frame(
  GID = shapefile$GID,
  NPP = shapefile$NPP,
  SPEED = shapefile$SPEED,
  density = shapefile$density,
  Lat = centroid[, "X"],
  Lon = centroid[, "Y"]
)