Learn R Programming

R.AlphA.Home (version 2.0.2)

root: Get Root Directory of Current Source File

Description

Returns the directory path where the current source code file is located, optionally the full file path, or builds a path relative to it.

This function is especially useful when the same source code is used by multiple users, each using their own environment with different file paths. It helps avoid writing full paths in raw text inside source codes by dynamically retrieving the location of the currently active source file in RStudio.

Usage

root(..., includeFName = FALSE)

Value

A character string representing either:

  • The absolute path of the directory containing the current source file (default)

  • The full absolute path including the filename (if includeFName = TRUE)

  • A path built from the root directory and the provided components (if ... given)

Arguments

...

Path components to append to the root directory. If empty, returns only the directory path. If provided, builds a path using file.path().

includeFName

Logical. If TRUE, returns the full file path including the filename instead of just the directory. Ignored if ... is provided.

Examples

Run this code
if (FALSE) {
# Get only the directory path of the current source file
my_dir <- root()
print(my_dir)
# Example output: "/home/user/my_project/R"

# Get the full path including filename
my_file <- root(includeFName = TRUE)
print(my_file)
# Example output: "/home/user/my_project/R/my_script.R"

# Build a path relative to root
data_path <- root("data", "input.csv")
print(data_path)
# Example output: "/home/user/my_project/R/data/input.csv"
}

Run the code above in your browser using DataLab