下面是示例数据。似乎很基本,但我在网上搜索没有得到明确的答案。在这种情况下,我如何创建一个新的数据帧,其中区域名称在末尾只有短语MSA,而不是MicroSA或其他可能性。
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)
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
另一个选择是使用stringi
:
library(dplyr)
testitem %>%
filter(stringi::stri_endswith_fixed(areaname, "MSA"))
areaname Employment
1 Albany NY MSA 100
2 Albany GA MSA 104
3 Reno NV MSA 112
4 Syracuse NY MSA 88
或者您可以使用grepl
:
library(dplyr)
testitem %>%
filter(grepl("MSA$", areaname))
或使用endsWith
:
testitem %>%
filter(endsWith(areaname, "MSA"))