R getwd() and setwd() Functions - Working Directory
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:
-
dir The new working directory path (a string).
Example
Get the current working directory
current_dir
<-
getwd
(
)
(
paste
(
"Current working directory:"
, current_dir
)
)
View directory contents
(
"Directory file list:"
)
(
list.files
(
)
)
Set the working directory (example)
setwd("/Users/username/projects/runoob")
View the R installation directory
(
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