使用 read_sf 读取 shp 并转换为 data.frame

Reading shp with read_sf and converting to data.frame

我正在阅读几个 .shp 文件,我想在最后将它们合并(绑定行)到一个 sf 数据框中。我尝试了几件事,但结果不是 sf 数据框,几何单元格是列表格式。

可重现的例子:

library(tidyverse)
library(sf)  

# create sample sf data frames and export them to directory: /folder/
data1 <- data.frame(attr = c(1:10), lon = c(11:20), lat = c(21:30)) %>% 
  st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326) 
data1 %>% write_sf("folder/data1.shp")
data2 <- data.frame(attr = c(11:20), lon = c(21:30), lat = c(31:40)) %>% 
  st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4326) 
data2 %>% write_sf("folder/data2.shp")

# function for reading the exported files
read_files <- function(filename){
 table <- read_sf(filename)
}

# getting the exported .shp files from the same directory
file_list <- list.files("folder/", pattern = ".shp", full.names = T)

# reading 
df <- map_df(file_list, read_files)  

如有任何建议,我们将不胜感激。

问题是 purrr::map_df 使用 dplyr::bind_rows 绑定 data.frames,它不能很好地处理 sfc 列或单位 class 列。 因此警告:

Warning messages:
1: In bind_rows_(x, .id) :
  Vectorizing 'sfc_POINT' elements may not preserve their attributes

相反,您可以像这样使用基本 rbind(请注意,您可以直接使用 st_read 而不是 read_files):

df <- do.call(rbind, lapply(file_list, st_read))

有关详细信息,请参阅此讨论: https://github.com/tidyverse/dplyr/issues/2457