Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R grep() Function - Pattern Matching and Searching

R grep() Function - Pattern Matching and Searching

R Language Examples R Language Examples

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:

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 the matching values

print

(

"Fruits containing 'ap':"

)

print

(

grep

(

"ap"

, fruits, value

=

TRUE

)

)

grepl: Return a logical vector

print

(

"Whether it contains 'ap':"

)

print

(

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"

)

,

  Email

=

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

$email

)

,

]

print

(

"Users with a runoob email:"

)

print

(

runoob_users

)

The output of the code above is:

[1] "runoob 邮箱的用户:"

  姓名              邮箱

1 张三 zhang@runoob.com

3 王五  wang@runoob.com

R Language Examples R Language Examples