Tom
Tom

Reputation: 2341

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?

Upvotes: 5

Views: 152

Answers (5)

Chris
Chris

Reputation: 2286

and perhaps

dat$var[which(grepl('string', dat$var) == TRUE)] 
[1] "thisstring"  "otherstring"

Upvotes: 0

akrun
akrun

Reputation: 886978

Using str_subset

library(stringr)
str_subset(dat$var, "string")
[1] "thisstring"  "otherstring"

Upvotes: 3

Quinten
Quinten

Reputation: 41225

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

Upvotes: 4

langtang
langtang

Reputation: 24722

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

Ouptut:

[1] "thisstring"  "otherstring"

Upvotes: 6

Ma&#235;l
Ma&#235;l

Reputation: 51914

Use value = TRUE in grep:

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

Upvotes: 7

Related Questions