Search code examples
rstringmatchgrepl

Creating a vector of string matches


I have data as follows:

library(data.table)
dat <- fread("id var
              1  thisstring
              2  otherstring
              3  notthisone")

I am trying to get a vector of all strings in column var that contain string.

If I do:

grepl("string", dat$var)

I get:

[1] TRUE TRUE FALSE

What I want to get is:

matches <-  c("thisstring", "otherstring")

How should I do this?


Solution

  • Use value = TRUE in grep:

    grep("string", dat$var, value = TRUE)
    #[1] "thisstring"  "otherstring"