Get continent name from country name in R

前端 未结 3 761
猫巷女王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:37

    You can try

    my.df <- data.frame(country = c("Afghanistan","Algeria"),
                        continent= as.factor(c("Asia","Africa")))
    merge(my.df, raster::ccodes()[,c("NAME", "CONTINENT")], by.x="country", by.y="NAME", all.x=T)
    #       country continent CONTINENT
    # 1 Afghanistan      Asia      Asia
    # 2     Algeria    Africa    Africa
    

    Some country values might need an adjustment; I dunno since you did not provide all values.

提交回复
热议问题