Ram
Ram

Reputation: 29

using list.files to read many shape files and then merge them into one big file

I have more than 1000 shape files in a directory, and I want to select only 10 of them whose names are already known to me as follows:

15TVN44102267_Polygons.shp, 15TVN44102275_Polygons.shp
15TVN44102282_Polygons.shp, 15TVN44102290_Polygons.shp
15TVN44102297_Polygons.shp, 15TVN44102305_Polygons.shp
15TVN44102312_Polygons.shp, 15TVN44102320_Polygons.shp
15TVN44102327_Polygons.shp, 15TVN44102335_Polygons.shp

First I want to read only these shape files using the list.files command, and then merge them into one big file. I tried the following command, but it failed. I will appreciate any assistance from the community.

setwd('D/LiDAR/CHM_tree_objects')
files <- list.files(pattern="15TVN44102267_Polygons|
15TVN44102275_Polygons|    15TVN44102282_Polygons|
15TVN44102290_Polygons|    15TVN44102297_Polygons|
15TVN44102305_Polygons|    15TVN44102312_Polygons|
15TVN44102320_Polygons|    15TVN44102327_Polygons|
15TVN44102335_Polygons|    15TVN44102342_Polygons|
15TVN44102350_Polygons|    15TVN44102357_Polygons",
recursive = TRUE, full.names = TRUE)

Upvotes: 2

Views: 2337

Answers (1)

Stewart Macdonald
Stewart Macdonald

Reputation: 2142

Here's a slightly different approach. If you already know the location of the files and their file names, you don't need to use list.files:

library(sf)

baseDir <- '/temp/r/'
filenames <- c('Denisonia-maculata.shp', 'Denisonia-devisi.shp')
filepaths <- paste(baseDir, filenames, sep='')

# Read each shapefile and return a list of sf objects
listOfShp <- lapply(filepaths, st_read)

# Look to make sure they're all in the same CRS
unique(sapply(listOfShp, st_crs))

# Combine the list of sf objects into a single object
combinedShp <- do.call(what = sf:::rbind.sf, args=listOfShp)

combinedShp will then be an sf object that has all the features in your individual shapefiles. You can then write that out to a single file in your chosen format with st_write.

Upvotes: 5

Related Questions