【问题标题】:convert csv to shp in r where geometry is in single column将 csv 转换为 r 中的 shp,其中几何位于单列中
【发布时间】:2021-11-25 21:56:41
【问题描述】:

我有一个 csv 文件,其中包含单列中的点几何信息。给定几何列的格式,是否有一种直接的方法可以将 csv 转换为 r 中的空间数据文件(我可以在 QGIS 中执行此操作,或者可以将列拼接成 x 和 y,但我很好奇是否有更好的方法)。

以下是数据的示例:

name <- c("A", "B", "C")
geom <- c("POINT (45.095914704767 -93.266719775361)",
          "POINT (45.095220489232 -93.254896591796)",
          "POINT (45.079643666 -93.257941333)")
dat <- data.frame(name, geom)
dat

【问题讨论】:

    标签: r spatial wkt


    【解决方案1】:

    几何图形的格式“POINT (45, -93)”就是所谓的Well-Known Text,它是几何图形的标准表示。

    {sf} 库可以直接读取 Well-Known Text (WKT)

    library(sf)
    
    sf::st_as_sf(x = dat, wkt = "geom")
    
    # Simple feature collection with 3 features and 1 field
    # Geometry type: POINT
    # Dimension:     XY
    # Bounding box:  xmin: 45.07964 ymin: -93.26672 xmax: 45.09591 ymax: -93.2549
    # CRS:           NA
    # name                       geom
    # 1    A POINT (45.09591 -93.26672)
    # 2    B  POINT (45.09522 -93.2549)
    # 3    C POINT (45.07964 -93.25794)
    

    【讨论】:

    • 不错的答案!谢谢!
    【解决方案2】:

    使用基本正则表达式(和 sf):

    library(sf)
    
    dat$y <- gsub(pattern = ".*\\((-?[0-9.]+).*", replacement= "\\1", dat$geom)
    dat$x <- gsub(pattern = ".*\\s(-?[0-9.]+).*", replacement= "\\1", dat$geom)
    dat_sf <- st_as_sf(dat, coords = c("y","x"))
    st_write(dat_sf, "dat.shp")
    
    Created on 2021-10-05 by the reprex package (v2.0.1)
    

    【讨论】:

      【解决方案3】:

      如果您的几何列实际​​上被格式化为字符串,您可以使用dplyr 去除多余的文本,然后使用sf 包将坐标转换为点列:

      library(magrittr)
      dat %>%
        dplyr::mutate(
          # replace text and parenthesis
          geom = stringr::str_replace(geom, 'POINT \\(', ''),
          geom = stringr::str_replace(geom, '\\)', '')
        ) %>%
        # separate into lat and lon columns
        tidyr::separate(geom, into=c('lon', 'lat'), sep=' ') %>%
        # convert to sf point object 
        # (assuming this is in WGS84, but you can specify any CRS here)
        sf::st_as_sf(coords = c('lat', 'lon'), crs=4326)
      

      如果您能够将 .csv 保存为 .geojson 或 .shp 文件,则可以使用 sf::read_sf('path/to/your/data.shp') 函数将其读入 R。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-04
        • 1970-01-01
        • 2020-08-18
        • 2017-06-08
        • 2020-10-01
        • 1970-01-01
        • 2023-03-27
        相关资源
        最近更新 更多