如何将国家/地区代码转换为国家/地区

时间:2017-08-08 12:46:22

标签: r converter country-codes

这是我可重现的代码:

library(tidyverse)
library(eurostat)
library(countrycode)

#Query eurostat data set
search <- search_eurostat("road", type = "table")

#Accessing "People killed in road accidents" data set.
df <- get_eurostat("tsdtr420")

#Create a data frame filtered on most recent data (2015)
accidents2015 <- df %>%
  filter(time == "2015-01-01") 

codes <- select(accidents2015, geo)

countrycode(sourcevar = codes, "iso2c", "country_name")

当最后一行运行时,我收到以下错误消息:

  

条件的长度> 1,国家代码中只使用第一个元素错误(sourcevar = codes,&#34; iso2c&#34;,&#34; country_name&#34;):         sourcevar必须是字符或数字向量。

2 个答案:

答案 0 :(得分:0)

首先codes是一个数据框,你需要传递一个向量,即使用数据框的列。此外,将类从因子更改为字符。最后是"country.name"而不是"country_name"

codes$geo = as.character(codes$geo)

countrycode(sourcevar = codes$geo, "iso2c", "country.name")


[1] "Austria"        "Belgium"        "Switzerland"    "Cyprus"         "Czech Republic" "Germany"        "Denmark"       
 [8] "Estonia"        NA               "Spain"          "Finland"        "France"         "Croatia"        "Hungary"       
[15] "Iceland"        "Italy"          "Lithuania"      "Luxembourg"     "Latvia"         "Malta"          "Netherlands"   
[22] "Norway"         "Poland"         "Portugal"       "Romania"        "Slovenia"       NA  

答案 1 :(得分:0)

  1. 传递一个向量,而不是数据帧/ tibble作为sourcevar

  2. 使用country.name,而不是country_name作为目标代码

  3. 在您的具体情况下,您最好使用eurostat作为原始代码

  4. 例如......

    library(tidyverse)
    library(eurostat)
    library(countrycode)
    
    accidents2015 <- 
      get_eurostat("tsdtr420") %>%
      filter(time == "2015-01-01")
    
    countrycode(sourcevar = accidents2015$geo, "eurostat", "country.name")
    
相关问题