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

时间:2018-03-27 12:18:33

标签: r dataframe sf

我正在阅读几个.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)  

任何建议都表示赞赏。

Desired and current output

1 个答案:

答案 0 :(得分:4)

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

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

相反你可以像这样使用base rbind(注意你可以直接使用st_read而不是read_files):

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

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