R Advanced

R basename() Function

The basename() is a base R function that extracts the last component (or the ‘base name’) of a file or directory path and returns the name of the file or directory. So, if you have a path like “/Users/krunallathiya/Desktop/Code/pypro/data.pdf, basename() would return “data.pdf.

The opposite function of basename() is dirname(), which gives the directory part of the path.

Syntax

basename(path)

Parameters

Name Value
path It takes a path as input and strips away the directory parts, leaving just the filename.

Getting a file from the file path

Let’s define a file path of the current working directory + file name.

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

basename(dir)

# [1] "Pro.R"

Getting a directory from the file path

What if we just pass the directory path and do not include the file? We will pass the directory path in which the file is residing. How about that? What will the function return? Well, this function will return the last directory part of the full path. So, it is not just for getting files but also for getting directories.

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

basename(dir)

Output

[1] "R"

Relative Paths

The basename() function works well with relative paths.

basename("../scripts/data.R")

# [1] "data.R"

Multiple Paths (Vectorized)

Let’s take a vector of file paths and pass that vector to the function.

paths <- c("/Documents/file1.txt", "/var/log/documents/file2.log")

basename(paths)

# [1] "file1.txt" "file2.log"

That’s it!

Recent Posts

How to Check If File and Folder Already Exists in R

Whether you are reading or writing files via programs in the file system, it is…

1 day ago

How to Check Data type of a Variable in R

When it comes to checking the data type of a variable, it depends on what…

2 days ago

Mastering grepl() Function in R

The grepl() function (stands for "grep logical") in R searches for patterns within each element…

3 days ago

zip(), unzip() and tar(), untar() Functions in R

The zip() function creates a new zip archive file. You must ensure that the zip tool…

4 days ago

How to Create Directory and File If It doesn’t Exist in R

When working with file systems, checking the directory or file existence is always better before…

5 days ago

How to Create a Grouped Boxplot in R

To create a grouped boxplot in R, we can use the ggplot2 library's aes() and…

7 days ago