【问题标题】:Convert sf object to dataframe and restore it to original state将 sf 对象转换为数据框并将其恢复为原始状态
【发布时间】:2021-10-12 12:47:50
【问题描述】:

我想将 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 对象恢复到原始状态?

【问题讨论】:

  • 在设置几何图形时(在最后),试试这个:st_as_sf(geo_df, wkt = "geom", crs = 4326)
  • @Skaqqs 非常感谢,问题解决了!!!
  • 不客气!您介意我将其发布为答案,以便将来的读者更容易找到吗?

标签: r sf


【解决方案1】:

我认为geom 不是st_geometry 所期望的格式。 st_as_text 将您的几何图形转换为 WKT,如帮助中所述:

简单要素几何的返回 WKT 表示符合简单要素访问规范和扩展,称为 EWKT,由 PostGIS 和其他简单要素实现支持,用于将 SRID 添加到 WKT 字符串。

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

改为使用st_as_sf(wkt=) 设置新(旧)几何体。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2011-04-06
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多