我有一个名称的特征向量,并希望准确地识别每个元素是否包含一个城市名称。为了实现这一点,我最初使用了下面的代码:
name <- c( "Business Applications for New York" ,"Proprietors' Farm Income in New York" ,"Farm Business (Included in Nonfinancial Corporate and Noncorporate Business Sectors); Nonresidential Structures, Current Cost Basis, Transactions")
library(maps)
city=c()
for (j in 1:length(name)) {
testresult=c()
for (i in 1:length(us.cities$name)) {
testresult[i] = agrepl(us.cities$name[i], name[j], max.distance=3, ignore.case=TRUE,fixed = T)
}
if (sum(testresult>0)) {
city[j]=1
} else{
city[j]=0 }
}
city
然而,这段代码错误地推断出name vector中的所有元素都包含城市名称。有没有更好的方法来准确地检测R中字符向量的每个元素中的城市名称?您的见解和代码示例将不胜感激。谢谢你,谢谢!
1条答案
按热度按时间h43kikqp1#
在这种情况下,一种方法可以是利用固有的
state.abb
,其中包含状态缩写,并使用gsub
和paste(..., collapse = "|")
从map
的数据集us.cities$name
中删除这些缩写。然后使用grepl
查看是否匹配:(Note
trimws
修剪与此gsub
关联的白色空间)