如何在 R 中添加带有区域和 iso(用于映射)的新列?

how to add new columns with region and iso(for mapping) in R?

我当前的数据包含名为 "Country" 的 126 个国家/地区的列和其他一些列。我正在尝试创建名为 "Continent" 的新列,国家的大陆,以及 "Country Code",国家的 iso 映射代码。我目前的代码有问题。

 military_dta <-read_csv("Military Spending_Raw.csv")

 glimpse(military_dta)

 military_dta1 <- military_dta %>% drop_na()

 install.packages("countrycode")

 library(countrycode)

 military_dta1$continent <- countrycode(sourcevar = military_dta1[,
 "Country"],
                             origin = "country.name",
                             destination = "continent")

这是我得到的错误:

Error in countrycode(sourcevar = military_dta1[, "Country"], origin = "country.name", : sourcevar must be a character or numeric vector. This error often arises when users pass a tibble (e.g., from dplyr) instead of a column vector from a data.frame (i.e., my_tbl[, 2] vs. my_df[, 2] vs. my_tbl[[2]])

如错误所述,您传递的是小标题而不是列向量。试试这个...

military_dta1$continent <- countrycode(sourcevar = military_dta1$Country,
                             origin = "country.name",
                             destination = "continent")

或如错误消息所示...

military_dta1$continent <- countrycode(sourcevar = military_dta1[["Country"]],
                             origin = "country.name",
                             destination = "continent")