How to Use dirname() Function in R

The dirname() function in R is used to get the directory name of a file path.




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"



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


And the development version from GitHub with:

# install.packages("devtools")


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


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



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


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.

Leave a Comment