Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R getwd() and setwd() Functions - Working Directory

R getwd() and setwd() Functions - Working Directory

R Language Examples R Language Examples

The R getwd() function is used to get the current working directory, and setwd() is used to set the working directory.

The working directory is the default path R uses when reading and writing files.

The syntax of the two functions is as follows:

getwd()

setwd(dir)

Parameter Description:

Example

Get the current working directory

current_dir

<-

getwd

(

)

print

(

paste

(

"Current working directory:"

, current_dir

)

)

View directory contents

print

(

"Directory file list:"

)

print

(

list.files

(

)

)

Set the working directory (example)

setwd("/Users/username/projects/runoob")

View the R installation directory

print

(

paste

(

"R installation directory (R.home):"

,

R.home

(

)

)

)

Running the above code will display the current R working directory and the file list.

When reading or writing files, if only a file name is given (without a path), R will look for the file in the current working directory. To ensure code portability, it is recommended to set the correct working directory first.

R Language Examples R Language Examples