Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
In R, grep(pattern, x) finds elements of a character vector that match a pattern and returns their positions. Use value = TRUE for matching strings, or grepl() for TRUE/FALSE flags. The worked example below carries those results into a sample manifest while keeping missing identifiers separate from observed nonmatches.
What grep in R is used for in research
A useful starting point is a specific selection rule: keep records whose identifier begins with a site code, find column names containing a label, or inspect filenames with an expected suffix. These are text selection tasks. A matching label alone does not establish that a record belongs in an analysis; the inclusion rule still needs a scientific justification.
This guide uses an illustrative composite sample manifest. Its identifiers and measurements are invented for demonstration, with deliberate edge cases. The task is to select site A records, inspect what was excluded, and preserve the original rows. You can adapt that structure to an analysis script without adopting its fictional site convention.
The distinction between detecting and selecting matters. A flag can remain beside every observation; a selected vector contains fewer elements. Decide which object the next step needs before writing the search. For broader text transformations, the stringr cheat sheet for text cleaning in R maps related operations.
grep syntax and arguments
grep(pattern, x, ignore.case = FALSE, perl = FALSE,
value = FALSE, fixed = FALSE, useBytes = FALSE,
invert = FALSE)
The official signature puts the search pattern first and the input vector second. The defaults describe a case-sensitive regular-expression search returning positions. value changes the result to selected strings; invert changes the selection to nonmatches. These switches answer separate questions, so name them rather than relying on a sequence of unnamed TRUE and FALSE arguments.
The matching mode is another independent decision. fixed requests a literal search, while perl switches to Perl-compatible regular expressions. useBytes requests byte-by-byte matching rather than character-by-character matching. Leave it at its default for this example; a byte-oriented change is not a general solution for text containing different encodings. The regex manual explains the engines and syntax in detail.
For this manifest, the rule needs an initial anchor and case-insensitive matching. It needs neither a different regex engine nor byte matching. Keeping those decisions explicit makes it easier to review why the fourth example record was accepted and why the fifth was excluded.
Install or access
grep() belongs to R’s base package, so no add-on package is needed for the main example. If R is not installed, use the official CRAN software directory, which links to R binaries, sources and manuals. Work in an R session and save the commands together as a script.
Open the installed documentation with help(“grep”, package = “base”) and help(“regex”, package = “base”). The help system supports package-specific lookups, which is useful when another package offers similarly named functions. The examples explicitly use base::grep() and base::grepl() so their intended implementation is clear.
Keep the pattern and its purpose next to the selection code. For example, write down whether “site A” means a prefix, an exact identifier, or any occurrence of those letters. Those are different rules even when they happen to produce identical results on a small initial file.
Step-by-step task: select sample records
-
Create the illustrative composite manifest. Enter the following commands. The sixth record has a missing identifier; the fifth contains the target text in the wrong position.
samples = data.frame( sample_id = c("site-A_001", "site-B_002", "site-A_003", "SITE-A_004", "archive_site-A_005", NA, "control"), assay = c(10, 12, 11, 13, 15, 14, 9) ) pattern = "^site-A_"The initial caret anchors the pattern to the beginning. The underscore is part of this example’s site prefix, so a different separator would require a different rule.
-
Find positions before extracting rows. Name optional arguments explicitly.
idx = base::grep(pattern, samples$sample_id, ignore.case = TRUE) idx # [1] 1 3 4These are positions within the searched column. In this unchanged manifest they correspond to rows one, three and four. The archive record is excluded because its identifier begins with “archive”, even though it contains “site-A_” later.
-
Apply the positions to the original manifest. Data-frame indexing uses the position before the comma for rows and the position after it for columns.
selected = samples[idx, , drop = FALSE] selected # sample_id assay # 1 site-A_001 10 # 3 site-A_003 11 # 4 SITE-A_004 13The blank column index keeps every column. The explicit drop = FALSE keeps a data frame when the selection is later narrowed to a single column. Do not reuse idx after independently sorting or filtering samples; calculate it against the object you are selecting from.
-
Return labels or flags when those are the required output. These two calls answer different downstream needs.
base::grep(pattern, samples$sample_id, ignore.case = TRUE, value = TRUE) # [1] "site-A_001" "site-A_003" "SITE-A_004" hit = base::grepl(pattern, samples$sample_id, ignore.case = TRUE) hit # [1] TRUE FALSE TRUE TRUE FALSE FALSE FALSEUse the labels for inspection and the flags for a row-aligned check. The uppercase identifier stays uppercase in the selected values; the matching rule accepts its case variation without rewriting the stored identifier.
-
Separate missing IDs from observed nonmatches. Here, a missing identifier must remain visible as its own review category.
missing_id = is.na(samples$sample_id) missing_records = samples[missing_id, , drop = FALSE] other_records = samples[!missing_id & !hit, , drop = FALSE]missing_records contains original row six. other_records contains rows two, five and seven. This is an editorial workflow choice: an unavailable identifier is not affirmative evidence of membership in another site.
Output and how to read it
The R Core reference distinguishes the three outputs used above: positions from grep(), whole matching elements when value = TRUE, and logical flags from grepl(). A position is an element number, not the character offset of the match inside its string. Returning “site-A_001” also does not extract only the “site-A_” substring.
Check the worked example as a partition of its original seven rows: three selected records, one missing-ID record and three observed nonmatches. The assay measurements remain attached to their original identifiers. This provides a practical check on the row selection without implying anything about the invented assay values.
R’s extraction documentation allows logical indices and recycles them when necessary. Consequently, keep a flag tied to the exact input vector that produced it. A flag calculated on one version of a dataset should not be applied after rows have been rearranged elsewhere. Keeping the manifest and selection code together makes that relationship inspectable.
To select columns by their names, put the resulting indices after the comma: samples[, base::grep(“^assay”, names(samples)), drop = FALSE]. This searches the column names, then selects columns. By contrast, samples[idx] uses a single data-frame index and selects columns rather than the sample rows intended above. The guide to removing columns in R develops that distinction further.
The downloadable data table below compares tasks, calls and output shapes across the documented functions. It is a reference for deciding which object to request; it is separate from the worked manifest and the alternatives table.
Troubleshooting
Missing values appear among the excluded records
For a nonmissing pattern, base R treats NA input elements as nonmatching. Therefore, invert = TRUE can select missing identifiers alongside observed nonmatches. In the example, base::grep(pattern, samples$sample_id, ignore.case = TRUE, invert = TRUE) yields positions 2, 5, 6 and 7. Keep the explicit missing_id category when those cases need different treatment.
Do not assume every string-processing package makes the same missing-value choice. The startsWith() documentation explicitly demonstrates a difference from grepl() for missing input. Check that edge case before substituting one implementation into an established script.
The search accepts too much or too little
According to R’s regex reference, ^ and $ anchor the beginning and end, | introduces alternatives, parentheses group expressions, and {n} requests an exact repetition count. For this fictional naming convention, ^site-A_[[:digit:]]{3}$ accepts an entire ID with exactly three digits. It rejects appended notes that the prefix-only rule accepts.
For two accepted site prefixes, ^(site-A|site-B)_ groups the alternatives under the initial anchor. Test a positive example, an observed nonmatch and a near miss such as the archive identifier. Those examples expose the intended boundary more clearly than a long list containing only accepted records.
A period or another punctuation mark changes the match
Regular expressions give punctuation special meanings. For a literal substring search, use fixed = TRUE. For a regex suffix such as a filename extension, write “[.]csv$” in an R string: the bracketed period matches a literal period, and the dollar sign anchors the end. With fixed = TRUE, the brackets and dollar sign are literal too, so that mode does not implement this suffix rule.
Several patterns do not run as separate searches
The base grep documentation says a pattern vector of length two or more uses its first element with a warning. Use one deliberate expression with alternatives for a combined rule. If separate rules serve different purposes, give each its own call and name rather than passing a vector and assuming every pattern was evaluated.
For repeated use, put the selection rule into a documented function with clear inputs. CASRAI’s guide to defining functions in R covers that structure. Preserve small expected examples beside the rule so a later change to the naming convention can be checked.
Free alternatives
The alternatives here are R functions for the same text task. The official stringr references document detection and subsetting separately: str_detect() returns logical flags, while str_subset() returns matching strings. Both put the input strings before the pattern and interpret the pattern as a regex by default.
| Alternative | Documented operation | Example for nonmissing input |
|---|---|---|
| base::startsWith() | Test a literal prefix; returns logical values. | startsWith(c(“site-A_001”, “site-B_002”), “site-A_”) |
| base::endsWith() | Test a literal suffix; returns logical values. | endsWith(c(“table.csv”, “notes.txt”), “.csv”) |
| stringr::str_detect() | Detect a pattern; returns a logical vector. | stringr::str_detect(c(“site-A_001”, “site-B_002”), “^site-A_”) |
| stringr::str_subset() | Select whole strings containing a match. | stringr::str_subset(c(“site-A_001”, “site-B_002”), “^site-A_”) |
startsWith() and endsWith() are useful when the rule is literally a prefix or suffix: punctuation in that prefix or suffix does not need regex interpretation. They do not express the complete three-digit ID rule shown above. Their documentation also describes recycling inputs, so supply the intended prefix or suffix explicitly.
For stringr, fixed() requests fixed-string interpretation and negate = TRUE reverses selection or detection. Its references distinguish fixed matching from locale-aware collation for human text. A sample-code rule using ASCII labels should not silently become a rule for matching personal names or multilingual free text. Choose the operation and matching assumptions together, then inspect the returned object.
Sources
- R Core Team, Pattern Matching and Replacement. Checked 2026-11-14.
- R Core Team, Regular Expressions as used in R. Checked 2026-11-14.
- R Core Team, Extract or Replace Parts of an Object. Checked 2026-11-14.
- R Core Team, Extract or Replace Parts of a Data Frame. Checked 2026-11-14.
- R Core Team, Does String Start or End With Another String?. Checked 2026-11-14.
- stringr developers, Detect the presence/absence of a match. Checked 2026-11-14.
- stringr developers, Find matching elements. Checked 2026-11-14.
- CRAN, Software and documentation directory; R Core Team, Documentation: help. Checked 2026-11-14.
Data: R pattern-search tasks and output shapes
Original task-to-output crosswalk compiled from R Core and stringr reference documentation. It distinguishes selecting element positions, selecting whole strings, preserving logical flags and testing literal boundaries. Calls use generic x and pattern inputs rather than study observations.
| Task | Documented call | Output | Reference |
|---|---|---|---|
| Select matching positions | base::grep(pattern, x) | Positions of matching elements | R Core: Pattern Matching and Replacement |
| Select matching strings | base::grep(pattern, x, value = TRUE) | Whole matching elements as a character vector | R Core: Pattern Matching and Replacement |
| Retain one flag per input element | base::grepl(pattern, x) | Logical match flags | R Core: Pattern Matching and Replacement |
| Test a literal prefix | base::startsWith(x, prefix) | Logical prefix flags; shorter inputs are recycled | R Core: startsWith/endsWith |
| Test a literal suffix | base::endsWith(x, suffix) | Logical suffix flags; shorter inputs are recycled | R Core: startsWith/endsWith |
| Detect with string-first arguments | stringr::str_detect(x, pattern) | Logical vector | stringr: str_detect |
| Subset with string-first arguments | stringr::str_subset(x, pattern) | Character vector of matching whole elements | stringr: str_subset |
Sources
- R Core: Pattern Matching and Replacement (accessed 2026-11-14)
- R Core: startsWith/endsWith (accessed 2026-11-14)
- stringr: str_detect (accessed 2026-11-14)
- stringr: str_subset (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







