Search code examples
rlatitude-longituder-sfr-sp

shape file and sf data-frame geometry into latitude longitude columns


I have a simple shape file with multipolygons .shp file data

read data into R

shp <- st_read("/home/rdfleay/Desktop/R/WestAustralia/GeographeBay/data/gb_gensub50a.shp") # sf()

attempt projection, wanting lat lon, but data remains in meters..

shp_t <- st_transform(shp, crs = st_crs(shp))

project using 'standard' to get lat-lon

shp_4326 = st_transform(shp, "EPSG:4326") #

i am trying to get the geometry as columns of 'lat' & 'lon'

reef_GBay <- shp_4326 %>% 
   filter(Substrate == "Reef")

nrow(reef_GBay)

t(reef_GBay)

print(reef_GBay$geometry)

head(reef_GBay$geometry)

as.data.frame(reef_GBay)
head(reef_GBay$geometry)

so far the output remains a single row?? thanks for the help


Solution

  • Use st_coordinates() to get the matrix of coordinates and coerce it to data frame:

    url <- "https://data.imas.utas.edu.au/attachments/275f62b0-0b6c-4514-90c7-deeae423ab23/MarineFutures_GeographeBay_reef.zip"
    f <- "file.zip"
    download.file(url, f, mode = "wb")
    
    unzip(f, exdir = "junk", junkpaths = TRUE)
    
    library(sf)
    
    shp <- st_read("junk/gb_gensub50a.shp")
    #> Reading layer `gb_gensub50a' from data source 
    #> Simple feature collection with 4 features and 2 fields
    #> Geometry type: MULTIPOLYGON
    #> Dimension:     XY
    #> Bounding box:  xmin: 321407.5 ymin: 6279315 xmax: 339012.5 ymax: 6289742
    #> Projected CRS: GDA94 / MGA zone 50
    
    
    # To get lon/lat
    
    library(dplyr)
    
    df <- shp %>%
      # 1. Project to lon/lat
      st_transform(4326) %>%
      # Your filter
      filter(Substrate == "Reef") %>%
      # 2 Extract coordinates
      st_coordinates() %>%
      # 3 to table /tibble
      as.data.frame()
    
    head(df)
    #>          X         Y L1 L2 L3
    #> 1 115.1362 -33.59926  1  1  1
    #> 2 115.1362 -33.59937  1  1  1
    #> 3 115.1361 -33.59946  1  1  1
    #> 4 115.1361 -33.59946  1  1  1
    #> 5 115.1361 -33.59946  1  1  1
    #> 6 115.1361 -33.59949  1  1  1
    

    Created on 2022-06-16 by the reprex package (v2.0.1)