【问题标题】:Is there a package/function in R that will identify country/continent?R中是否有一个包/函数可以识别国家/大陆?
【发布时间】:2022-02-04 07:55:34
【问题描述】:

R 中是否有函数或包可以从字符串变量中提取相关国家及其对应的大陆?

变量中的每个观察都编码如下:


df<- c("random,thing,thing, United States", "site, level, state, information, Sweden")

等等等等。 国家是最后一个“,”分隔符之后的最后一项。我本质上想提取该项目或使用某种函数从这样的字符串中提取国家/地区。

然后我需要创建另一个包含相关大陆的列。所以最终的输出应该是这样的:


df2 <- data.frame(Country=c("United States", "Sweden), Continent= c("North America", "Europe")

df2 确实需要遵循确切的命名法,即美国可以写成 USA 或 United States of America - 我只需要某种功能/包来提取该国家/地区信息并在 R 中为我提供大陆。

非常感谢!

【问题讨论】:

  • 在没有包的情况下,你总是可以separate()第二个字符串",\\s?",然后把它转换成五列,最后一个是country。然后,您可以导入包含国家信息的数据集(包括continent),然后只需在country 上输入*_join()

标签: r country


【解决方案1】:

好的,两者都可以:

library(dplyr)
library(countrycode)

df<- c("random,thing,thing, United States", "site, level, state, information, Sweden")
df2 <- data_frame(Country =  sub('.*\\, ', '', df))
df2$Continent <- countrycode(sourcevar = df2$Country,
                             origin = "country.name",
                             destination = "continent")
df2

【讨论】:

  • CLUTCH,不知道如何使用 countrycode 包
猜你喜欢
  • 2011-07-23
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
相关资源
最近更新 更多