R Func Grep
# R grep() Function - Pattern Matching and Search
[ R Language Examples](https://example.com/r/r-examples.html)
The R grep() function is used to search for positions or values matching a specified pattern in a string vector.
grepl() is its logical version, returning TRUE/FALSE. Both support regular expressions.
The grep() function syntax 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**: Input string vector.
* **value**: Whether to return the matched value (TRUE), not just the index (FALSE). Default is FALSE.
* **ignore.case**: Whether 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("Contains 'ap':")
print(grepl("ap", fruits))
Executing the above code produces:
"Indices containing 'ap'" 1 4 5 "Fruits containing 'ap'" "apple" "grape" "pineapple" "Contains 'ap'" TRUE FALSE FALSE TRUE TRUE FALSE
grepl() combined with logical indexing can filter rows in a data frame:
## Example
# User data containing email
df<-data.frame(
Name =c("Zhang San", "Li Si", "Wang Wu", "Zhao Liu"),
Email =c("zhang@example.com", "li@gmail.com",
"wang@example.com", "zhao@yahoo.com"),
stringsAsFactors = FALSE
)
# Filter users with tutorial email
tutorial_users <-df[grepl("tutorial", df$Email), ]
print("Users with tutorial email:")
print(tutorial_users)
Executing the above code produces:
"Users with tutorial email:" Name Email1 Zhang San zhang@example.com3 Wang Wu wang@example.com
[ R Language Examples](https://example.com/r/r-examples.html)
[R gsub() Function - String Replacement](https://example.com/r/r-func-gsub.html)[](https://example.com/r/r-func-gsub.html)
[ByteArk Coding Plan supports Doubao, GLM, DeepSeek, Kimi, MiniMax and other mainstream large models, official direct supply stable and reliable. Configuration Guide Β₯9.9/month Immediate Activation](https://www.volcengine.com/activity/codingplan?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=tutorial)[iFlytek Starfire Coding Plan includes free model call quota, DeepSeek, GLM, Kimi, MiniMax, one-stop experience and deployment platform. Configuration Guide Β₯3.9/month Immediate Activation](https://maas.xfyun.cn/modelSquare?ch=maas_lm_l2E)
YouTip