Amy
Amy

Reputation: 7

subsetting data with rows that contain a certain string in r

I want to subset my data where the name ends in string TRUST, LIMITED, INC., CO

the data looks like this

name            date
abc TRUST       2018-01-01
123 Foundation  1997-02-06
Tim LIMITED     2002-06-04
SA INC.         1968-12-28
Yu Co           2005-01-24
Coca Cola Ltd.  1980-05-30

I have tried the following but it is not working for multiple conditions

df[grepl(paste0(c("TRUST", "LIMITED", "INC", "CO"), collapse = "|"), df$name), ]   

It also extracts the coca cola company row as well but I do not want that.

Upvotes: 0

Views: 90

Answers (1)

tmfmnk
tmfmnk

Reputation: 40181

You can try:

df[grepl(paste0(c("TRUST", "LIMITED", "INC"), collapse = "|"), df$name), ]

         name       date
1   abc TRUST 2018-01-01
3 Tim LIMITED 2002-06-04
4     SA INC. 1968-12-28

The same with str_detect():

df %>%
 filter(str_detect(name, paste0(c("TRUST", "LIMITED", "INC"), collapse = "|")))

Upvotes: 1

Related Questions