startsWith: Does String Start or End With Another String?

View source: R/startsWith.R

startsWithR Documentation

Does String Start or End With Another String?

Description

Determines if entries of x start with a string prefix, where strings are recycled to common lengths.

Usage

startsWith(x, prefix, trim=FALSE, ignore.case=FALSE)

Arguments

x

character vector whose “starts” are considered.

prefix

character vector, typicall of length one, i.e., a string.

trim

whether leading and trailing spaces should be removed from x before testing for a match.

ignore.case

whether case should be ignored when testing for a match.

Value

A logical vector, of “common length” of x and prefix, i.e., of the longer of the two lengths unless one of them is zero when the result is also of zero length. A shorter input is recycled to the output length.

Note

The base package provides the underlying startsWith function that performs the string comparison. The gdata package adds the trim and ignore.case features.

An alias function starts_with is also provided, equivalent to gdata::startsWith. Using starts_with in scripts makes it explicitly clear that the gdata implementation is being used.

Author(s)

Gregory R. Warnes greg@warnes.net

See Also

startsWith for the 'base' package implementation, grepl, substring

Examples

## Simple example
startsWith("Testing", "Test")

## Vector examples
s <- c("Testing", " Testing", "testing", "Texting")
names(s) <- s

startsWith(s, "Test")        # " Testing", "testing", and "Texting" do not match
startsWith(s, "Test", trim=TRUE)        # Now " Testing" matches
startsWith(s, "Test", ignore.case=TRUE) # Now "testing" matches

# Comparison
# gdata
startsWith(s, "Test", trim=TRUE)
startsWith(s, "Test", ignore.case=TRUE)
# base
startsWith(trimws(s), "Test")
startsWith(tolower(s), tolower("Test"))

warnes/gdata documentation built on Dec. 5, 2023, 12:20 a.m.