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 Check If File and Folder Already Exists in R

Whether you are reading or writing files via programs in the file system, it is…

16 hours ago

How to Check Data type of a Variable in R

When it comes to checking the data type of a variable, it depends on what…

2 days ago

Mastering grepl() Function in R

The grepl() function (stands for "grep logical") in R searches for patterns within each element…

3 days ago

zip(), unzip() and tar(), untar() Functions in R

The zip() function creates a new zip archive file. You must ensure that the zip tool…

4 days ago

How to Create Directory and File If It doesn’t Exist in R

When working with file systems, checking the directory or file existence is always better before…

5 days ago

How to Create a Grouped Boxplot in R

To create a grouped boxplot in R, we can use the ggplot2 library's aes() and…

7 days ago