To get the current path of the script in R, use the dirname() function. The dirname() method is helpful when you would like to set the working directory to the path of the current script programmatically. Then use the setwd() function to set a new path.
dirname() Function in R
The dirname() is an inbuilt R function that returns the directory name of a file path. The dirname() function takes filePath as an argument and returns the character vector of directories.
Syntax
dirname(fp)
Parameters
The dirname() function takes fp as a file path.
Return Value
The dirname() returns the character vector of directories.
Example
Let’s define a file path of the current working directory + file name and pass this to the dirname() function.
dir <- "/Users/krunal/Desktop/code/R/Pro.R"
dirname(dir)
Output
[1] "/Users/krunal/Desktop/code/R"
You can see from the output that the dirname() function returns the part of the path up to (but excluding) the last path separator, or “.” if there is no path separator.
The basename() function removes all of the paths up to the last path separator.
In both basename() and dirname() functions, the trailing file separators are removed before dissecting the path, and for the dirname() method, any trailing file separators are removed from the result.
Use fs package from tidyverse
The fs provides a cross-platform, uniform interface to file system operations.
You can install the released version of fs from CRAN with:
install.packages("fs")
And the development version from GitHub with:
# install.packages("devtools") devtools::install_github("r-lib/fs")
If we want a complete full path, we can use the fs package’s path_dir() function.
library("fs")
dir <- "/Users/krunal/Desktop/code/R/Pro.R"
path_dir(dir)
Output
[1] "/Users/krunal/Desktop/code/R"
That is it for dirname() Function in R.

Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.