basename() in R: How to Use basename() Function in R

To get the file name using R programming, use the basename() function. To get the current path of the script in R, use the dirname() function.

basename() Function in R

The basename() is a built-in R function that removes all paths up to and including the last path separator (if any). The dirname() function returns the part of the path up to but excluding the last path separator, or “.” if there is no path separator.

To get the only file name and not all of the path, use the basename() function in R.

Syntax

basename(path)

Parameters

The path is a character vector containing path names.

Example

Let’s define a file path of the current working directory + file name and pass this to the basename() function.

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

basename(dir)

Output

[1] "Pro.R"

You can see from the output that the basename() function returns the only filename from the path.

Let’s not pass the filename, just the directory path, and see what it will return?

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

basename(dir)

Output

[1] "R"

You can see that it will return the tail of the directory path, which is R in our example. So the basename() function returns the tail of the input argument.

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 to file name from the full path, we can use the fs package’s path_file() function.

library("fs")

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

path_file(dir)

Output

[1] "Pro.R"

That is it for basename() Function in R.

Leave a Comment