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

colSums(): Calculating the Sum of Columns of a Data Frame in R

The colSums() function in R calculates the sums of columns for numeric matrices, data frames,…

4 days ago

rowSums(): Calculating the Sum of Rows of a Matrix or Data Frame in R

The rowSums() function calculates the sum of values in each numeric row of a matrix,…

7 days ago

R View() Function

The View() is a utility function in R that invokes a more intuitive spreadsheet-style data…

2 weeks ago

summary() Function: Producing Summary Statistics in R

The summary() is a generic function that produces the summary statistics for various R objects,…

3 weeks ago

R paste() Function

The paste() function in R concatenates vectors after converting them to character. paste("Hello", 19, 21,…

4 weeks ago

paste0() Function in R

R paste0() function concatenates strings without any separator between them. It is a shorthand version…

4 weeks ago