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.
basename(path)
Name | Value |
path | It takes a path as input and strips away the directory parts, leaving just the filename. |
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"
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"
The basename() function works well with relative paths.
basename("../scripts/data.R")
# [1] "data.R"
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!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
The scale() function in R centers (subtracting the mean) and/or scales (dividing by the standard…
To rename a file in R, you can use the file.rename() function. It renames a…
The prop.table() function in R calculates the proportion or relative frequency of values in a…
The exp() is a built-in function that calculates the exponential of its input, raising Euler's…
The split() function divides the input data into groups based on some criteria, typically specified…
The colMeans() function in R calculates the arithmetic mean of columns in a numeric matrix,…