View source: R/get_path_segment.R
get_path_segment | R Documentation |
The get_path_segment
function extracts specific segments from file paths provided as character strings. Segments can be extracted from either the beginning or the end of the path, depending on the value of n
.
get_path_segment(paths, n = 1)
paths |
A 'character vector' containing file system paths
|
n |
Numeric index for segment selection
|
Sophisticated Path Segment Extraction Mechanism:
Comprehensive input validation
Path normalization and preprocessing
Robust cross-platform path segmentation
Flexible indexing with forward and backward navigation
Intelligent segment retrieval
Graceful handling of edge cases
Indexing Behavior:
Positive n
: Forward indexing from path start
- n = 1
: First segment
- n = 2
: Second segment
Negative n
: Reverse indexing from path end
- n = -1
: Last segment
- n = -2
: Second-to-last segment
Range extraction: Supports c(start, end)
index specification
Path Parsing Characteristics:
Standardizes path separators to '/'
Removes drive letters (e.g., 'C:'
)
Ignores consecutive '/'
delimiters
Removes leading and trailing separators
Returns NA_character_
for non-existent segments
Supports complex path structures
'character vector' with extracted path segments
Matching segments for valid indices
NA_character_
for segments beyond path length
Critical Operational Constraints:
Requires non-empty 'paths' input
n
must be non-zero numeric value
Supports cross-platform path representations
Minimal computational overhead
Preserves path segment order
tools::file_path_sans_ext()
File extension manipulation
# Example: Path segment extraction demonstrations
# Setup test paths
paths <- c(
"C:/home/user/documents", # Windows style path
"/var/log/system", # Unix system path
"/usr/local/bin" # Unix binary path
)
# Example 1: Extract first segment
get_path_segment(
paths, # Input paths
1 # Get first segment
)
# Returns: c("home", "var", "usr")
# Example 2: Extract second-to-last segment
get_path_segment(
paths, # Input paths
-2 # Get second-to-last segment
)
# Returns: c("user", "log", "local")
# Example 3: Extract from first to last segment
get_path_segment(
paths, # Input paths
c(1,-1) # Range from first to last
)
# Returns full paths without drive letters
# Example 4: Extract first three segments
get_path_segment(
paths, # Input paths
c(1,3) # Range from first to third
)
# Returns: c("home/user/documents", "var/log/system", "usr/local/bin")
# Example 5: Extract last two segments (reverse order)
get_path_segment(
paths, # Input paths
c(-1,-2) # Range from last to second-to-last
)
# Returns: c("documents/user", "system/log", "bin/local")
# Example 6: Extract first two segments
get_path_segment(
paths, # Input paths
c(1,2) # Range from first to second
)
# Returns: c("home/user", "var/log", "usr/local")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.