-2

Is is possible to find the names in a vector that contain either id OR group Or both in the example below?

I have used grepl() without success.

a = c("c-id" = 2, "g_idgroups" = 3, "z+i" = 4)


grepl(c("id", "group"), names(a)) # return name of elements that contain either `id` OR `group` OR both
rnorouzian
  • 7,397
  • 5
  • 27
  • 72

2 Answers2

2

You can use :

pattern <- c("id", "group")
grep(paste0(pattern, collapse = '|'), names(a), value = TRUE)
#[1] "c-id"      "g_igroups"

With grepl you can get logical value

grepl(paste0(pattern, collapse = '|'), names(a))
#[1]  TRUE  TRUE FALSE

A stringr solution :

stringr::str_subset(names(a), paste0(pattern, collapse = '|'))
#[1] "c-id"      "g_igroups"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • can I add another patter like `"id|group|grp"`? Also can we make the pattern not case-sensitive? `"id|group|grp"` = `"iD|Group|Grp"` = `"ID|GRoup|GRp"` . . .? – rnorouzian Oct 31 '20 at 08:34
  • Yes, you can add as many patterns as you want using `|`. To make it case insensitive you can set `ignore.case = TRUE` – Ronak Shah Oct 31 '20 at 08:39
0

Using str_detect:

> names(a)[str_detect(names(a), 'id|groups')]
[1] "c-id"       "g_idgroups"
> names(a)
[1] "c-id"       "g_idgroups" "z+i"       
> 
Karthik S
  • 11,348
  • 2
  • 11
  • 25