The dirname() function in R is used to extract the path to the directory from a full file path. Essentially, it returns the directory part of a file path, excluding the file name.
This function is often used in conjunction with other file-handling functions like basename() (which extracts the file name) and file.path() (for constructing file paths), and path.expand() (for expanding tilde-prefixed paths).
dirname(fp)
fp: It takes fp as a file path.
It returns the character vector of directories.
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"
dirname(dir)
Output
[1] "/Users/krunal/Desktop/code/R"
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:
install.packages("fs")
The development version from GitHub with:
# install.packages("devtools")
devtools::install_github("r-lib/fs")
library("fs")
dir <- "/Users/krunal/Desktop/code/R/Pro.R"
path_dir(dir)
Output
[1] "/Users/krunal/Desktop/code/R"
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 dplyr::slice() function subsets rows by their position or index within a data frame. If…
R vectors are atomic, which means they have homogeneous data types. They are contiguous in…
DataFrames are like tables that contain rows and columns. Each column can have a different…
Dates in R are stored as the number of days since 1970-01-01, so converting a…
In R, you can think of a vector as a series of values in a…
The dplyr filter() function in R subsets a data frame and retains all rows that…