Check if a veriable in a list

I have a very simple question.
But I do not know how to do.

A data frame "a" like:

   num abc
1   1   a,z
2   2   b
3   3   c,z
4   4   d,z
5   5   e
6   6   f,z
7   7   g

I know that how to find if a row in 'a$abc' is 'b' I can use

filter(a, abc =='b')

but how should I find if a row has 'z'?

Thank you!

library(stringr)

a[str_detect(a$abc, "z"),]

2 Likes

If you want to use just {base}, use grepl:

a <- (cbind(c(1,2,3,4,5,6,7),c("a,z","b","c,z","d,z","e","f,z","g")))
a <- as.data.frame(a)
colnames(a) <- c("num","abc")

# Your example using dplyr::filter to find "b"
dplyr::filter(a, abc == "b")
#>   num abc
#> 1   2   b

# using base::grepl to repeat that search "b" 
a[grepl("b",a$abc), ]
#>   num abc
#> 2   2   b


# and, your request, to find any "z"s
a[grepl("z",a$abc), ]
#>   num abc
#> 1   1 a,z
#> 3   3 c,z
#> 4   4 d,z
#> 6   6 f,z

Created on 2021-01-22 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.