Get and Set working directory (setwd / getwd) in R
Get and Set working directory in R, Your environment is always pointed to some working location when you use R.
To get the working directory and set the working directory in R, use the following functions:
Get the current working directory with getwd().
Set the current working directory with setwd(‘Path/To/Your/Folder’).
The examples below demonstrate how to utilize these functions in practice.
Get Working Directory
The getwd() function in R can be used to display the current working directory.
This simple function, which takes no arguments, returns the current working directory. This comes in very handy for debugging.
show the current directory
getwd()
[1] "D:/RStudio"
Set Working Directory
The setwd() function can then be used to change the working directory to a different location.
This one is straightforward. Use the setwd R function to change the current working directory. The new working directory is required as an input to the setwd function.
This can be defined in absolute terms (a specific path). You can also browse up to the parent directory by typing “..”.
create a new working directory
setwd('D:/RStudio/Binning/')
We can then use the getwd() function to get the current working directory to confirm that the working directory has changed:
show the current directory
getwd() “D:/RStudio/Binning "
View the Working Directory’s Files
We may use the list.files() function to inspect the file names within the directory once we’ve set the working directory:
count the number of files in the current directory
length(list.files())
[1] 146
in the working directory, see the first five file names
head(list.files())
[1] "Actual-Vs-Predicted-1.png" [2] "Aesthetics must be either length 1 or the same as the data.png" [3] "AIC in R.jpg" [4] "Airline Reporting.jpg" [5] "Anderson-Darling Test in R.png" [6] "Application of Bayes Theorem.jpg"
To see if a given file is in our current working directory, we can use the percent in percent operator:
Verify that the file ‘AIC in R.jpg ‘ is present in the working directory.
'AIC in R.jpg' %in% list.files()
[1] TRUE
The presence of a TRUE output value shows that the specified file is really in the current working directory.
Please keep in mind that the space between letters is very important; if there is any, the word will be counted as a distinct one.
Summary
getwd() is a command that is used to display the current working directory
setwd() is a command that is used to point to a specific directory list.
list.files are used to get everything in the directory or folders
QQ-plots in R: Quantile-Quantile Plots-Quick Start Guide » finnstats
Subscribe to our newsletter!