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

Calculating Natural Log using log() Function in R

The log() function calculates the natural logarithm (base e) of a numeric vector. By default,…

2 days ago

Dollar Sign ($ Operator) in R

In R, you can use the dollar sign ($ operator)  to access elements (columns) of…

2 weeks ago

Calculating Absolute Value using abs() Function in R

The abs() function calculates the absolute value of a numeric input, returning a non-negative (only…

3 weeks ago

Printing an Output of a Program in R

When working with R in an interactive mode, you don't need to use any functions…

4 weeks ago

How to Calculate Variance in R

To calculate the sample variance (measurement of spreading) in R, you should use the built-in…

1 month ago

tryCatch() Function in R

The tryCatch() function acts as a mechanism for handling errors and other conditions (like warnings…

1 month ago