The dirname() function in R is “used to get the directory name of a file path“.
Syntax
dirname(fp)
Parameters
fp: The dirname() function takes fp as a file path.
Return Value
The dirname() returns the character vector of directories.
Example: Simple program to demonstrate dirname() function
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 paths 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 the following:
install.packages("fs")
And the development version from GitHub with:
# install.packages("devtools")
devtools::install_github("r-lib/fs")
We can use the fs package’s path_dir() function if we want a complete full path.
library("fs")
dir <- "/Users/krunal/Desktop/code/R/Pro.R"
path_dir(dir)
Output
[1] "/Users/krunal/Desktop/code/R"
Conclusion
The dirname() function in R is used to get the directory name of a file path. For example, if you have a file path like “C:/Users/RStudio/Projects/data.csv”, then dirname() will return “C:/Users/RStudio/Projects”.
To get the current path of the script in R, you can use the “dirname()” function.
That is it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.