Here, we will discuss how to set the working directory and get the working directory in R with the setwd() and getwd() functions respectively.

It is important to also see the page on the basics of the R environment.

1 Setting the Working Directory in R

The first step to reading files in R can be to set the working directory to the folder that contains the file(s) you want to work on. By doing so, your output file(s), unless otherwise specified, will also be written into this folder.

To set the working directory, you can use the line of code below with slight differences between Windows OS and macOS.

Note the use of forward slash.

Setting the Working Directory for Windows OS:

setwd("C:/Users/Public/Statscodes/Rdata/read-files/")

Setting the Working Directory for macOS:

setwd("/Users/Public/Statscodes/Rdata/read-files/")

Your directory may be longer than "C:/Users/Public/Statscodes/Rdata/read-files/" or "/Users/Public/Statscodes/Rdata/read-files/", depending on where the folder you are trying to reference is located.

Also, you can set your working directory in RStudio without code by taking the following steps:

  • Create or choose a folder where you will store the files you want to work with if you do not have one already.

  • Use the menu options in RStudio to set the working directory by following Session > Set Working Directory > Choose Directory. After clicking on "Choose Directory", navigate to the folder of your choice.

2 Getting the Working Directory in R

You can get your working directory, before or after setting it, with the following line of code:

getwd()
[1] "C:/Users/Public/Statscodes/Rdata/read-files"

To check the files or folders in your working directory, you can use the following line of code which will list all the files:

dir()
 [1] "testdata.csv"      "testdata.dta"      "testdata.RData"   
 [4] "testdata.RDS"      "testdata.sas7bdat" "testdata.sav"     
 [7] "testdata.txt"      "testdata.xls"      "testdata.xlsx"    
[10] "testdata.xpt"     

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes