Home > database >  Creating a vector of string matches
Creating a vector of string matches

Time:11-18

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?

CodePudding user response:

Use value = TRUE in grep:

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

CodePudding user response:

dat[grepl("string",var),var]

Ouptut:

[1] "thisstring"  "otherstring"

CodePudding user response:

Another option using %like% like this:

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

dat$var[dat$var %like% 'string']
#> [1] "thisstring"  "otherstring"

Created on 2022-11-18 with reprex v2.0.2

  • Related