1
votes

I'm reading several .shp files and I want to merge (bind rows) them into one sf data frame at the end. I tried several things but the result is not sf dataframe and the geometry cells are be in a list format.

Reproducible example:

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)  

Any suggestions are appreciated.

Desired and current output

1
Please include the packages that need to be loaded to make the example reproducible. Where does e.g. map_df come from?Edzer Pebesma

1 Answers

4
votes

the problem is that purrr::map_df uses dplyr::bind_rows to bind the data.frames, which does not handle sfc columns or units class columns well. Thus the warning:

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

instead you can use base rbind like this (note you can just use st_read directly instead of read_files):

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

see this discussion for more info: https://github.com/tidyverse/dplyr/issues/2457