Useful Path Handling Functions in R

Photo by Birgit Held from Pexels

When writing Data Science and Data Analysis Scripts in R, not rarely one has to recursively search for files inside folders, test for their existence, create new folders or files, rename or move them, delete them, and perform many other miscellaneous actions around paths.

Here, I want to give you an overview of diverse path handling functions in base R, which are intuitive and pretty handy. May the listing serve you as a useful cheatsheet:

1. How to get/set the current directory in R

getwd()setwd("/to/dir")

2. How to dissect and access Path Name Components in R

# parent directory name
dirname(path)
# file name
basename(path)
# file extension ## note, these are not base R functions
## you have to install the packages
## preceding `::`
## e.g. by `install.packages("tools")
## or "rio" or "xfun"
## e.g. 'csv' for files ending with '.csv'
tools::file_ext(path) # or:
rio::file_ext(path) # or:
xfun::file_ext(path)
# split a path into its components
# "/a/b/c.txt" => c("a", "b", "c.txt")
split_path <- function(path) {
if (dirname(path) %in% c(".", path)) return(basename(path))
return(c(basename(path), split_path(dirname(path))))
}
# from here

3. How to join Path Components in R

file.path("/a", "b", "file.txt") ## "/a/b/file.txt"

4. How to recursively list Files in Folders in R

# folders
list.dirs(path = ".", full.names = TRUE, recursive = TRUE)
# files
list.files("/to/dir", pattern="\\.csv", full.names=TRUE, recursive=TRUE) ## pattern is regex

5. How to test for Existence of Files and Folders in R

# folders
dir.exists("/to/dir") # or file.exists("/to/dir")
# fileshere
file.exists("/to/file.txt")

6. How to create new Folders and Files in R

# folders
dir.create("/to/new/dir", recursive=TRUE)
# files
file.create("/to/file.txt")

7. How to (recursively) delete Files and Folders in R

# folders
unlink("/to/dir", recursive=TRUE)
# files
unlink("/to/file.txt")

8. How to copy Folders with contents and Files in R

# copy folder architecture recursively (not keeping original dates)
dir.create('/to/dir', recursive=TRUE)
file.copy("/from/dir/or/file.txt", "/to/dir", recursive=TRUE, copy.date=FALSE)

9. How to move and rename Folders and Files in R

# folder
file.copy(from = "/from/dir", to = "/to/dir",
overwrite = recursive,
recursive = FALSE,
copy.mode = TRUE)
unlink("/from/dir")
# so this is not actually a mv in the sense of unix commands,
# but a copy and delete recursively
# files
file.rename("from", "to")
# or one could also copy first the file and then unlink() the original one.

10. How to get the size and creation time of Folders and Files in R

obj <- file.info(path)
# watch available variables by
str(obj)
# file size
obj$size
# is path a directory?
obj$isdir
# modification, creation, access time
obj$mtime, obj$ctime, obj$atime

The platform-dependent path separator in R, one can get by .Platform$file.sep which corresponds to Python’s os.sep.

However, I just saw that tidyverse has — like always — a more consistent and more complete set of functions also for this topic (see e.g. here).

Please feel free to comment if you know better solutions than the presented.

--

--

--

Code tweaker + Human Geneticist (Ph.D.) | Join medium by: https://gwang-jin-kim.medium.com/membership

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Park Planner: Part 1

Life is Learning

How To Use Voice Generator For Twitch Livestreams

Is There Any Text-To-Speech Solution With License Rights for Comercial Purposes?

Coupling, Cohesion, And Continuous Delivery Architecture

How to Perform a System Restore from Command Prompt Windows 10/7?

Zero Downtime Deployment of BusinessWorks Container Edition with Kubernetes — Part 5

Using Amazon Elastic Container Registry

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gwang Jin Kim

Gwang Jin Kim

Code tweaker + Human Geneticist (Ph.D.) | Join medium by: https://gwang-jin-kim.medium.com/membership

More from Medium

Uniform Distribution using Chi-Squared Test For Goodness of Fit in R Programming and Hand…

Mastermind board game for R Language

Central Limit Theorem In Statistics

Standard Errors