8

I have a folder with about 100 point shapefiles that are locations obtained while scat sampling of an ungulate species. I would like to merge all these point shapefiles into one shapefile in R. All the point data were in .gpx format initially which I then changed to shapefiles.

I am fairly new to R,so I am very confused as on how to do it and could not find codes that merged or combined more than a few shapefiles. Any suggestions would be much appreciated. Thanks!

V.Menon
  • 81
  • 1
  • 1
  • 3
  • 1
    See: https://gis.stackexchange.com/questions/264250/merge-two-shapefiles-in-r?rq=1. And note that [gis.se] might be a better place to ask future questions about shapefiles. – MrFlick Nov 27 '18 at 19:57
  • Also possible duplicate here: https://stackoverflow.com/questions/19961898/append-combine-shape-files – MrFlick Nov 27 '18 at 19:57
  • 3
    Welcome to SO! Can you provide a bit more info (i.e. when you read them what spatial type are they?; are you using sp/rgdal or sf? when you say "merge" what exactly do you mean output-wise/what if there are duplicates?). Also, this might be better served on https://gis.stackexchange.com – hrbrmstr Nov 27 '18 at 19:58

3 Answers3

13

Building on @M_Merciless .. for long lists you can use

all_schools <- do.call(rbind, shapefile_list)

Or, alternatively, the very fast:

all_schools <- sf::st_as_sf(data.table::rbindlist(x))
bevingtona
  • 301
  • 2
  • 6
11
library(sf)

list all the shapefiles within the folder location

file_list <- list.files("shapefile/folder/location", pattern = "*shp", full.names = TRUE)

read all shapefiles, store as a list

shapefile_list <- lapply(file_list, read_sf)

append the separate shapefiles, in my example there are 4 shapefiles, this can probably be improved by using a for loop or apply function for a longer list.

all_schools <- rbind(shapefile_list[[1]], shapefile_list[[2]], shapefile_list[[3]], shapefile_list[[4]])
M_Merciless
  • 379
  • 6
  • 12
1

Adding a solution that I think is "tidier"

library(fs)
library(tidyverse)

# Getting all file paths
shapefiles <- 'my/data/folder' |>
  dir_ls(recurse = TRUE) |>
  str_subset('.shp$')

# Loading all files
sfdf <- shapefiles |>
  map(st_read) |>
  bind_rows()

Admittedly, more lines of code but personally I think the code is much easier to read and comprehend this way.

JanLauGe
  • 2,297
  • 2
  • 16
  • 40