将 sf 对象转换为数据框并将其恢复到原始状态

Convert sf object to dataframe and restore it to original state

我想将 sf 对象转换为 dataframe 并将其恢复到原始状态。但是当我对 st_as_text(st_sfc(stands_sel$geometry)) 进行转换时,显示很难再次检索它。在我的例子中:

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") :  

               

请帮忙把我的 stands_sf 对象恢复到原始状态?

我认为 geom 不是 st_geometry 期望的格式。 st_as_text 按照帮助中的讨论将您的几何图形转换为 WKT:

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

相反,使用 st_as_sf(wkt=) 设置新(旧)几何图形。

st_as_sf(geo_df, wkt = "geom", crs = 4326)