R grep() function - pattern matching and searching

R 语言实例R language examples

R grep() function is used to search a character vector for positions or values that match a specified pattern.

grepl() is its logical version, returning TRUE/FALSE. Both support regular expressions.

The syntax of the grep() function is as follows:

grep(pattern, x, value = FALSE, ignore.case = FALSE)
grepl(pattern, x, ignore.case = FALSE)

Parameter description:

  • patternThe pattern to match (supports regular expressions).

  • xInput character vector.

  • valueWhether to return the matched value (TRUE) instead of just the index (FALSE). Default is FALSE.

  • ignore.caseWhether to ignore case.

Example

fruits <- c("apple", "banana", "orange", "grape", "pineapple", "mango")

# grep: return indices containing "ap"
print("Indices containing 'ap':")
print(grep("ap", fruits))

# grep with value: return matched values
print("Fruits containing 'ap':")
print(grep("ap", fruits, value = TRUE))

# grepl: return logical vector
print("Whether it contains 'ap':")
print(grepl("ap", fruits))

Executing the above code produces the following result:

[1] "包含 'ap' 的索引:"
[1] 1 4 5
[1] "包含 'ap' 的水果:"
[1] "apple"     "grape"     "pineapple"
[1] "是否包含 'ap':"
[1]  TRUE FALSE FALSE  TRUE  TRUE FALSE

grepl() combined with logical indexing can filter rows in a data frame:

Example

# User data with email addresses
df <- data.frame(
Name= c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu"),
Email= c("[email protected]", "[email protected]",
           "[email protected]", "[email protected]"),
  stringsAsFactors = FALSE
)

# Filter users with example emails
example_users <- df[grepl("example", df$Email), ]
print("example email users:")
print(example_users)

Executing the above code produces the following result:

[1] "example 邮箱的用户:"
  姓名              邮箱
1 张三 [email protected]
3 王五  [email protected]

R 语言实例R language examples

Other extensions