Site icon R-bloggers

Copying files with R

[This article was first published on Amy Whitehead's Research » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Following on from my recent experience with deleting files using R, I found myself needing to copy a large number of raster files from a folder on my computer to a USB drive so that I could post them to a colleague (yes, snail mail – how old and antiquated!).  While this is not typically a difficult task to do manually, I didn’t want to copy all of the files within the folder and there was no way to sort the folder in a sensible manner that meant I could select out the files that I wanted without individually clicking on all 723 files (out of ~4,300) and copying them over.  Not only would this have been incredibly tedious(!), it’s highly likely that I would have made a mistake and missed something important or copied over files that they didn’t need. So enter my foray into copying files using R.

R has a nice set of file manipulation commands in the base package that make it really easy to find out if a file exists (file.exist), rename files (file.rename), copy them to a different directory (file.copy) or delete them (file.delete).  Basically, you point R at the directory where your files live, identify the files that you want to manipulate and then tell it what you want to do to them.  In my case, I wanted to identify all Geo-tiff formatted rasters whose filenames ended in “SDM” and copy them to a new directory.

# identify the folders
current.folder <- "C:/Where my files currently live"
new.folder <- "H:/Where I want my files to be copied to"

# find the files that you want
list.of.files <- list.files(current.folder, "SDM.tif$")

# copy the files to the new folder
file.copy(list.of.files, new.folder)

This will chug away for a bit (time for a coffee, anyone?) and then produce a vector of TRUE/FALSE the same length as your list.of.files that identifies whether it was able to copy them or not.  Pretty simple really.  The only tricky bit can be getting the regex pattern right to pull out the files you want to manipulate. There are many regex guides online – I often head over to Rubular to test a pattern if I’m having trouble (note that it’s actually designed for Ruby and not R but they seem similar enough that it has always worked so far).


To leave a comment for the author, please follow the link and comment on their blog: Amy Whitehead's Research » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.