dirname() Function in R with Example

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.




The dirname() function takes fp as a file path.

Return Value

The dirname() returns the character vector of directories.


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"



[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:


And the development version from GitHub with:

# install.packages("devtools")


If we want a complete full path, we can use the fs package’s path_dir() function.


dir <- "/Users/krunal/Desktop/code/R/Pro.R"



[1] "/Users/krunal/Desktop/code/R"

That is it for dirname() Function in R.


Leave a Comment