Get continent name from country name in R

前端 未结 3 803
猫巷女王i
猫巷女王i 2021-01-11 16:10

I have a data frame with one column representing country names. My goal is to add one more column which gives the continent information. Please check the following use case:

3条回答
  •  半阙折子戏
    2021-01-11 16:40

    You can use the countrycode package for this task.

    library(countrycode)
    df <- data.frame(country = c("Afghanistan",
                                 "Algeria",
                                 "USA",
                                 "France",
                                 "New Zealand",
                                 "Fantasyland"))
    
    df$continent <- countrycode(sourcevar = df[, "country"],
                                origin = "country.name",
                                destination = "continent")
    #warning
    #In countrycode(sourcevar = df[, "country"], origin = "country.name",  :
    #  Some values were not matched unambiguously: Fantasyland
    

    Result

    df
    #      country continent
    #1 Afghanistan      Asia
    #2     Algeria    Africa
    #3         USA  Americas
    #4      France    Europe
    #5 New Zealand   Oceania
    #6 Fantasyland      
    

提交回复
热议问题