Home > Mobile >  Convert sf object to dataframe and restore it to original state
Convert sf object to dataframe and restore it to original state

Time:10-13

I'd like to convert a sf object to a dataframe and restore it to its original state. But when I make the conversion of st_as_text(st_sfc(stands_sel$geometry)) is shows very difficult to retrieve it again. In my example:

library(sf)

# get AOI in shapefile
download.file(
  "https://github.com/Leprechault/trash/raw/main/sel_stands_CMPC.zip",
  zip_path <- tempfile(fileext = ".zip")
)
unzip(zip_path, exdir = tempdir())

# Open the file
setwd(tempdir())
stands_sel <- st_read("sel_stands_CMPC.shp")
st_crs(stands_sel) = 4326

# Extract geometry as text
geom <- st_as_text(st_sfc(stands_sel$geometry))

# Add the features
features <- st_drop_geometry(stands_sel)
str(features)

# Joining feature   geom 
geo_df <- cbind(features, geom)
str(geo_df)
# 'data.frame': 2 obs. of  17 variables:
#  $ CD_USO_SOL: num  2433 9053
#  $ ID_REGIAO : num  11 11
#  $ ID_PROJETO: chr  "002" "344"
#  $ PROJETO   : chr  "BARBA NEGRA" "CAMPO SECO"
#  $ CD_TALHAO : chr  "159A" "016A"
#  $ CARACTERIS: chr  "Plantio Comercial" "Plantio Comercial"
#  $ CARACTER_1: chr  "Produtivo" "Produtivo"
#  $ CICLO     : int  2 1
#  $ ROTACAO   : int  1 1
#  $ DATA_PLANT: chr  "2008/04/15" "2010/04/15"
#  $ LOCALIDADE: chr  "BARRA DO RIBEIRO" "DOM FELICIANO"
#  $ ESPACAMENT: chr  "3.00 x 2.50" "3.5 x 2.14"
#  $ ESPECIE   : chr  "SALIGNA" "DUNNI"
#  $ SISTEMA_PR: chr  "MACRO ESTACA - EUCALIPTO" "SEMENTE - EUCALIPTO"
#  $ VLR_AREA  : num  8.53 28.07
#  $ ID_UNIQUE : chr  "BARBANEGRA159A" "CAMPOSECO016A"
#  $ geom      : chr  "MULTIPOLYGON (((-51.21423 -30.35172, -51.21426 -30.35178, -51.2143 -30.35181, -51.21432 -30.35186, -51.21433 -3"| __truncated__ 

# Return to original format again
stands_sf <- geo_df %>% 
                        st_geometry(geom) %>% 
                             sf::st_as_sf(crs = 4326)
#Error in UseMethod("st_geometry") :  

               

Please, any help to restore my stands_sf object to the orinal state?

CodePudding user response:

I think geom isn't in a format st_geometry is expecting. st_as_text converted your geometry into WKT as discussed in the help:

The returned WKT representation of simple feature geometry conforms to the simple features access specification and extensions, known as EWKT, supported by PostGIS and other simple features implementations for addition of SRID to a WKT string.

https://r-spatial.github.io/sf/reference/st_as_text.html

Instead, use st_as_sf(wkt=) to set the new (old) geometry.

st_as_sf(geo_df, wkt = "geom", crs = 4326)
  •  Tags:  
  • r sf
  • Related