Home > other >  How to filter by a given phrase in a single column in R
How to filter by a given phrase in a single column in R

Time:07-06

Below is the sample data. Seems pretty basic but my internet searches have not yielded a clear answer. In this case, how would I create a new data frame where the areaname only has the phrase MSA at the end and not MicroSA or other possibilities.

  areaname <- c("Albany NY MSA", "Albany GA MSA", "Aberdeen SD MicroSA", "Reno NV MSA", "Fernley NV MicroSA", "Syracuse NY MSA")
  Employment <- c(100,104,108,112,116,88)

   testitem <- data.frame(areaname, Employment)

CodePudding user response:

testitem %>%
  filter(stringr::str_ends(areaname, "MSA"))


         areaname Employment
1   Albany NY MSA        100
2   Albany GA MSA        104
3     Reno NV MSA        112
4 Syracuse NY MSA         88

CodePudding user response:

Another option is to use stringi:

library(dplyr)

testitem %>%
  filter(stringi::stri_endswith_fixed(areaname, "MSA"))

Output

         areaname Employment
1   Albany NY MSA        100
2   Albany GA MSA        104
3     Reno NV MSA        112
4 Syracuse NY MSA         88

Or you can use grepl:

library(dplyr)

testitem %>%
  filter(grepl("MSA$", areaname))

Or use endsWith:

testitem %>%
  filter(endsWith(areaname, "MSA"))
  • Related