2017-08-08 138 views
0

這裏是我的重複性代碼:如何國家代碼轉換成國名

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,只有第一元素將在countrycode中使用錯誤(sourcevar = codes,「iso2c」,「country_name」): sourcevar必須是字符或數字向量。

回答

0
  1. 傳遞一個矢量,而不是一個數據幀/ tibble作爲sourcevar

  2. 使用country.name,不country_name作爲目的地代碼

  3. 在你的具體情況,你最好用eurostat作爲起源碼

例如...

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

accidents2015 <- 
    get_eurostat("tsdtr420") %>% 
    filter(time == "2015-01-01") 

countrycode(sourcevar = accidents2015$geo, "eurostat", "country.name") 
+0

非常感謝!你給出了最好的答案! – Tdebeus

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 
+0

還不能確定EL,但英國應該GB轉換正確 – Olivia

+1

謝謝您的回答! – Tdebeus