R Advanced

R dirname() Function

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).

Syntax

dirname(fp)

Parameters

fp: It takes fp as a file path.

Return Value

It returns the character vector of directories.

Example: Basic usage of dirname() function

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"

Using the 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 the following:

install.packages("fs")

The development version from GitHub with:

# install.packages("devtools")

devtools::install_github("r-lib/fs")

We can use the fs package’s path_dir() function if we want a complete full path.

library("fs")

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

path_dir(dir)

Output

[1] "/Users/krunal/Desktop/code/R"

That’s it!

Recent Posts

How to Set and Get Working Directory [setwd() and getwd()] in R

Set the current working directory The setwd() function sets the working directory to the new…

2 days ago

Standard deviation in R [Using sd() Function]

The sd() function in R calculates the sample standard deviation of a numeric vector or…

3 days ago

R dnorm(): Probability Density Function

The dnorm() function in R calculates the value of the probability density function (pdf) of…

4 days ago

R rep() Function: Repeating Elements of a Vector

R rep() is a generic function that replicates elements of vectors and lists for a…

1 week ago

Splitting Strings: A Beginner’s Guide to strsplit() in R

The strsplit() function in R splits elements of a character vector into a list of…

1 week ago

Understanding of rnorm() Function in R

The rnorm() method in R generates random numbers from a normal (Gaussian) distribution, which is…

2 weeks ago