Finding and Setting The Working Directory

The function getwd() will tell you the current working directory. If you wish to set a different working directory, use this:

setwd("C:\\Users\\uroy\\Documents\\R\\learning")

Note that the backslash needs to be escaped with another backslash immediately before it. Alternatively, you could do this:

setwd("C:/Users/uroy/Documents/R/learning")

Check whether a folder/file exists

Do this to check if a folder called “Week1” exists in the current working directory:

file.exists("./Week1")              
## [1] FALSE
# Returns TRUE if the folder exists, and FALSE otherwise.
# file.exists("Week1") and file.exists("C:/Users/uroy/Documents/R/learning/Week1") are equivalent

One can check whether a bunch of folders/files exist, with one command:

file.exists(c("./Week1", "heights.html", "heights.Rmd"))
## [1] FALSE  TRUE  TRUE

So, the folder “Week1” doesn’t exist, but the two files do. Most R commands that work with a scalar will also work with a vector.

Create a folder/file (after checking it doesn’t already exist)

If a folder doesn’t, create an empty folder of that name:

if (!file.exists("./Week1")) {dir.create("./Week1")}

Do this to create an empty file called brillaint.R in the Week1 directory, if such a directory exists:

if (file.exists("Week1")) {file.create("Week1/brilliant.R")}
## [1] TRUE

Remove a folder/file (after checking it exists)

Here’s how to remove a file, after checking that it exists:

if (file.exists("Week1/brilliant.R")) {file.remove("Week1/brilliant.R")}
## [1] TRUE

… or to remove the entire Week1 folder if it exists:

if (file.exists("./Week1")) {unlink("./Week1", recursive = TRUE)}

Of course, you can then use file.exists("./Week1") to verify that the removal went through.

Rename files (after checking that they exist)

list.of.files <- c("heights.html", "heights.Rmd")
if (file.exists(list.of.files)) {file.rename(from = list.of.files, to = c("Heights.html", "Heights.Rmd"))}
## [1] TRUE TRUE

Copy files from one folder to another

The file.copy() command allows you to copy a bunch of files from one folder to another (in this case the temp subdirectory of the working directory), and, optionally, rename the copies:

list.of.files.2 <- c("temp/tempheights.html", "temp/tempheights.Rmd")
file.copy(from = list.of.files, to = list.of.files.2)
## [1] FALSE FALSE

List the Files and Sub-Folders in a Folder

The list.files() and list.dirs() commands do this job.

folders <- c("data", "animation")
# Lists all folders in the "data" and "animation" subfolders
list.dirs(folders)
# Lists all files in the "data" and "animation" subfolders of the working directory
list.files(folders)

The End