R grep() Function - Pattern Matching and Searching
The R grep() function is used to search a vector of strings for the positions or values matching 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:
-
pattern The pattern to match (supports regular expressions).
-
x The input vector of strings.
-
value Whether to return the matching values (TRUE) rather than just the indices (FALSE). Default is FALSE.
-
ignore.case Whether to ignore case.
Example
fruits
<-
c
(
"apple"
,
"banana"
,
"orange"
,
"grape"
,
"pineapple"
,
"mango"
)
grep: Return indices containing "ap"
(
"Indices containing 'ap':"
)
(
grep
(
"ap"
, fruits
)
)
grep with value: Return the matching values
(
"Fruits containing 'ap':"
)
(
grep
(
"ap"
, fruits, value
=
TRUE
)
)
grepl: Return a logical vector
(
"Whether it contains 'ap':"
)
(
grepl
(
"ap"
, fruits
)
)
The output of the code above is:
[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"
)
,
=
c
(
"zhang@runoob.com"
,
"li@gmail.com"
,
"wang@runoob.com"
,
"zhao@yahoo.com"
)
,
stringsAsFactors
=
FALSE
)
Filter users with a runoob email
runoob_users
<-
df
[
grepl
(
"runoob"
,
df
)
,
]
(
"Users with a runoob email:"
)
(
runoob_users
)
The output of the code above is:
[1] "runoob 邮箱的用户:"
姓名 邮箱
1 张三 zhang@runoob.com
3 王五 wang@runoob.com
R Language Examples