Skip to main content
v2026.11,986 entries · CC-BY 4.0

grep in R: Syntax, Arguments and Worked Example

Find sample IDs with grep() in R, select matching rows, compare output types and keep missing identifiers separate from observed nonmatches.

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

  1. 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.

  2. Find positions before extracting rows. Name optional arguments explicitly.

    idx = base::grep(pattern, samples$sample_id, ignore.case = TRUE)
    idx
    # [1] 1 3 4
    

    These 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.

  3. 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    13
    

    The 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.

  4. 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 FALSE
    

    Use 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.

  5. 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

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.

R pattern-search tasks and output shapes
TaskDocumented callOutputReference
Select matching positionsbase::grep(pattern, x)Positions of matching elementsR Core: Pattern Matching and Replacement
Select matching stringsbase::grep(pattern, x, value = TRUE)Whole matching elements as a character vectorR Core: Pattern Matching and Replacement
Retain one flag per input elementbase::grepl(pattern, x)Logical match flagsR Core: Pattern Matching and Replacement
Test a literal prefixbase::startsWith(x, prefix)Logical prefix flags; shorter inputs are recycledR Core: startsWith/endsWith
Test a literal suffixbase::endsWith(x, suffix)Logical suffix flags; shorter inputs are recycledR Core: startsWith/endsWith
Detect with string-first argumentsstringr::str_detect(x, pattern)Logical vectorstringr: str_detect
Subset with string-first argumentsstringr::str_subset(x, pattern)Character vector of matching whole elementsstringr: str_subset

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about grep in R: Syntax, Arguments and Worked Example

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →