Setting working directory in R

One of the first things a social scientist does is put data and programs into a folder on their computer.  The reason for having a well-identified folder (and not going to the default temporary folder a program might set up) is that then the folder can be copied and backed up.  Macs and increasingly Windows want to make the folder structure opaque, fearing that if you knew where the folder was you might accidentally delete it. So they prefer to keep the folders somewhat opaque and back them up themselves.

But we know better.  So here is the code for setting up a working directory in R

For Windows: setwd(“C:/Users/MKevane/Google Drive/data/Rstuff”)
For Mac: setwd(“/Users/MKevane/Google Drive/data/Rstuff”)

I often use R on two computers and they have different user names so a script that tells R to identify the computer first and then set the directory is more general.  For example:

# This is my code for setting the working directory
# First I define my two possible directories on my two machines
# as well as the subdirectory where the files are
mainDir1 <- “C:/Users/MKevane”
mainDir2 <- “C:/Users/Michael Kevane”
subDir <- “/Google Drive/data/Rstuff”

# Then I tell R to pick whichever one the actual machine is
# and set that as the working directory
if (file.exists(mainDir1)){
setwd(file.path(mainDir1, subDir))
} else {
if (file.exists(mainDir2)){
setwd(file.path(mainDir2, subDir))

#check the directory with

About mkevane

Economist at Santa Clara University and Director of Friends of African Village Libraries.
This entry was posted in Politics. Bookmark the permalink.