【问题标题】:Error uploading spatial data to existing RPostgreSql table using sf::st_write() in R使用 R 中的 sf::st_write() 将空间数据上传到现有 RPostgreSql 表时出错
【发布时间】:2023-01-19 15:20:24
【问题描述】:

我使用主键和外键创建了以下 RPostgreSql 表:

create table
us_hurricanes (
    id         serial                        primary key
  , geo_id     int                           references geo_id_master_list(geo_id)
  , storm_id   text                          not null
  , timestamp  timestamp with time zone      not null
  , radii      int                           not null
  , geom       geometry(multipolygon, 2163)  not null
);

它目前包含一些观察结果。在R,我正在尝试使用 sf::st_write() 函数将其他条目上传到表中:

db <- RPostgreSQL::dbConnect(
    dbDriver("PostgreSQL"),
    dbname = NAME,
    host = HOST,
    port = PORT,
    user = USER,
    password = PASS)

sf::st_write(
    new_data, 
    dsn = db, 
    layer = "us_hurricanes",
    append = TRUE)

其中 new_data 是一个数据框,其中包含与 us_hurricanes 表中所有相同的字段,geom 列是一个 CRS 为 2163 的 sfc_POLYGON 对象。

Simple feature collection with 1 feature and 5 fields
Geometry type: POLYGON
Dimension:     XY
Bounding box:  xmin: 2628189 ymin: -2026100 xmax: 3092784 ymax: -1531227
Projected CRS: US National Atlas Equal Area
    id geo_id storm_id           timestamp radii                           geom
1 3210   3210 al072022 2022-09-21 12:00:00    34 POLYGON ((2783123 -1544385,...

当我运行上面的 st_write() 函数时,出现以下非描述性错误:

Error in nchar(sm[1L], type = "w") : invalid multibyte string, element 1

一些观察:

  • 如果我在st_write() 函数中使用新表名作为layer 值,不会发生错误。相反,它在我的数据库中创建了一个新表,但该表的 SRID 为 0。
  • 如果我不使用append = TRUE 参数,表将被成功覆盖。
  • 如果我将数据帧写入 shapefile,使用 shp2pgsql 创建一个 .sql 文件,并通过命令行运行该文件,新条目将成功上传到现有表。

我该如何解决这个问题?在 R 中是否有更好的选择来将新的空间条目上传到现有的 Postgres 表?

【问题讨论】:

  • 如果您的问题在顶部列出了所有已加载的包,那将会有所帮助。

标签: r postgresql postgis sf


【解决方案1】:

您是否尝试过使用更新的RPostgres 包而不是RPostgreSQL 打开数据库连接?

来自help(st_write): “我们正式测试对 RPostgres::Postgres() 连接的支持”。

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2019-06-09
    • 2022-08-05
    • 2023-03-29
    • 2018-05-21
    • 2019-03-07
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多