R How to Match Globbing Pattern & Character String (4 Examples)

In this article you’ll learn how to perform matching with globbing or wildcard patterns in the R programming language.

Constructing Example Data

wc <- "AAA*"                               # Wildcard string 
vec <- c("AAAy", "BBBx", "AAA5", "xyz")    # Character string vector

Example 1: Get Position of Matching Wildcard Pattern

grep(wc, vec)                              # Apply grep() function
# [1] 1 3

Example 2: Get Character Strings that Match Wildcard Pattern

grep(wc, vec, value = TRUE)                # Apply grep() function & value argument
# [1] "AAAy" "AAA5"

Example 3: Get Logical Values Corresponding to Matching Wildcard Pattern

grepl(wc, vec)                             # Apply grepl()
# [1]  TRUE FALSE  TRUE FALSE

Example 4: Create Data Subset of Elements that Match Wildcard Pattern

vec_subset <- vec[grepl(wc, vec)]          # Create vector subset
vec_subset                                 # Print subset
# [1] "AAAy" "AAA5"

Related Articles & Further Resources

Have a look at the following R programming language tutorials. They explain topics such as data conversion, character strings, and extracting data:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top