0

I am trying to merge 300 dataframes (these are polygons) into a single dataframe. I know how to do it two by two using rbind. Given the high number of dataframes I am looking for a way to merge them all together. Every dataframe has the same structure. One example:

Simple feature collection with 1 feature and 3 fields geometry type: POLYGON dimension: XY bbox: xmin: 18.62278 ymin: 2.720688 xmax: 18.68717 ymax: 2.773334 epsg (SRID): 4326 proj4string: +proj=longlat +datum=WGS84 +no_defs id
source year geometry 1 2 HUELS POLYGON ((18.66028 2.773334...

# Load Data - EXCEL
shp_list<-(read_excel(".repository.xlsx",sheet="repos",skip=0))

# Loop to load shapefiles
for (s in 1:length(shp_list$shapefile)){

varName<-print(paste(shp_list$shapefile[s]))

  assign(varName,st_read(print(paste("./",gsub("trmc_","",shp_list$original_map[s]),"/",sep ="")),paste(shp_list$shapefile[s])))
}
1
1

As rcs mentioned you may use bind_rows which receives a list object of data.frames and binds them all together:

library(sf)
library(dplyr)

file_list = list.files("shapefile_folder", pattern = "\\.shp", full.names = T)

geodf_list = lapply(file_list,  function(x) read_sf(x))

geodf = bind_rows(geodf_list)

besides that, when using for loops you should preallocate the vector with vector(mode = list, length = list_length) to avoid copying all the object at every iteration; or use lapply

1
  • 1
    If you don't want to pull dplyr in then do.call(rbind, lapply(.....)) works just as well and is only using base R functions.
    – Spacedman
    Mar 26 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.