r之从字符串到正则表达式再到新字符串
我有一个数据框,其中包含一列杂乱的字符串。每个杂乱的字符串都包含其中某处的单个国家/地区的名称。这是一个玩具版本:
df <- data.frame(string = c("Russia is cool (2015) ",
"I like - China",
"Stuff happens in North Korea"),
stringsAsFactors = FALSE)
感谢 countrycode 包,我还有第二个数据集,其中包含两个有用的列:一个包含国家名称的正则表达式 (regex),另一个包含相关的国家名称(country.name)。我们可以像这样加载这个数据集:
library(countrycode)
data(countrycode_data)
我想编写代码,使用 countrycode_data$regex 中的正则表达式来识别 df$string 每一行中的国家/地区名称;将该正则表达式与 countrycode_data$country.name 中的正确国家名称相关联;最后,将该名称写入新列 df$country 中的相关位置。执行此 TBD 操作后,df 将如下所示:
string country
1 Russia is cool (2015) Russian Federation
2 I like - China China
3 Stuff happens in North Korea Korea, Democratic People's Republic of
我不太清楚如何做到这一点。我已经尝试使用 grepl、which、tolower 和 %in% 的各种组合,但我弄错方向或尺寸(或两者)。
请您参考如下方法:
这正是 countrycode 包的目的,所以没有理由自己重新编码。就像这样使用它......
library(countrycode)
df <- data.frame(string = c("Russia is cool (2015) ", "I like - China",
"Stuff happens in North Korea"), stringsAsFactors = FALSE)
df$country.name <- countrycode(df$string, 'country.name', 'country.name')
特别是在这种情况下,它不会找到“Stuff happens in North Korea”的明确匹配项,但这实际上是朝鲜和韩国正则表达式的问题(我在这里打开了一个问题 https://github.com/vincentarelbundock/countrycode/issues/139 ) .否则,您想要做的事情原则上应该可行。
(特别针对@ulfelder 的旁注:新版本的countrycode 刚刚在CRAN 上发布,v0.19。自从我们添加了新语言以来,列名称发生了一些变化,因此 country.name 现在是 country.name.en,regex 现在是 country.name.en.regex)
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。



