5.3 C
London
Thursday, December 19, 2024
HomeRImport & Export Data in RHow to Use setwd / getwd in R (With Examples)

How to Use setwd / getwd in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Whenever you use R, your environment is always pointed to some working directory.

You can use the following functions in R to get the working directory and set the working directory:

  • getwd() – Get the current working directory
  • setwd(‘Path/To/Some/Directory’) – Set current working directory

The following examples show how to use these functions in practice.

Example 1: Get Working Directory

We can use the getwd() function to display the current working directory in R:

#display current working directory
getwd()

[1] "C:/Users/Bob/Desktop"

Example 2: Set Working Directory

We can then use the setwd() function to set the working directory to some new location:

#set working directory
setwd('C:/Users/Bob/Documents')

We can then verify that the working directory has changed by using the getwd() function again to get the current working directory:

#display current working directory
getwd()

"C:/Users/Bob/Documents"

Example 3: View Files in Working Directory

Once we’ve set the working directory, we can use the list.files() function to view the file names within the directory:

#view number of files in working directory
length(list.files())

[1] 147

#view first five file names in working directory
head(list.files())

"output.yml"  "analysis3.R"  "analysis3-1.R"  "testdoc.R"  "final_model2.Rmd" 

We can also use the %in% operator to check if a specific file is located in our current working directory:

#check if file 'analysis3.R' exists in working directory
'analysis3.R' %in% list.files()
[1] TRUE

An output value of TRUE indicates that the specific file is indeed located in the current working directory.

Additional Resources

The following tutorials explain how to perform other common functions in R:

How to Manually Enter Raw Data in R
How to Import CSV Files into R
How to Import Excel Files into R
How to Fix in R: cannot change working directory

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories