我正在使用我发现的一些旧代码来获取字符串(例如:)
[1] "Indianapolis, IN" "Columbia, TN" "Chicago, IL" "Next door to Florida Man"
[5] "Holeintheroad, TN" "RUCH 11 LISTOPADA"
并找出其中有州缩写的。我有以下内容:
user_info$location[user_info$location!=""&!is.na(user_info$location)] %>%
str_match(sprintf("(%s)",paste(state.abb,collapse="|"))) %>%
.[,2] %>%
table() %>%
broom::tidy() %>%
set_names(c("NAME","n")) %>%
as.data.frame() -> tweet_states_abbr
其中 datasets::state.abb 是:
[1] "AL" "AK" "AZ" "AR" "CA" "CO" "CT" "DE" "FL" "GA" "HI" "ID" "IL" "IN" "IA" "KS" "KY" "LA" "ME" "MD" "MA" "MI" "MN" "MS"
[25] "MO" "MT" "NE" "NV" "NH" "NJ" "NM" "NY" "NC" "ND" "OH" "OK" "OR" "PA" "RI" "SC" "SD" "TN" "TX" "UT" "VT" "VA" "WA" "WV"
[49] "WI" "WY"
问题是 str_match() 获取了太多信息——除了诸如“IN”或“CA”之类的实际状态缩写之外,它还获取了部分单词(例如:在“MAGA”中,它获取了“MA”或“GA”)。我知道正则表达式可以解决这个问题,但我不确定如何将它们与 sprintf 和 %s 合并到这里,因为它们不是原生 R——所以我不确定在哪里放置 \b 或 \s。有什么建议吗?谢谢!