Reputation: 2341
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
Reputation: 2286
and perhaps
dat$var[which(grepl('string', dat$var) == TRUE)]
[1] "thisstring" "otherstring"
Upvotes: 0
Reputation: 886978
Using str_subset
library(stringr)
str_subset(dat$var, "string")
[1] "thisstring" "otherstring"
Upvotes: 3
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
Reputation: 24722
dat[grepl("string",var),var]
Ouptut:
[1] "thisstring" "otherstring"
Upvotes: 6
Reputation: 51914
Use value = TRUE
in grep
:
grep("string", dat$var, value = TRUE)
#[1] "thisstring" "otherstring"
Upvotes: 7