R数据框列到矢量,就像字典

时间:2017-02-02 01:29:14

标签: r dataframe

在R中,向量可以像某些语言称为“地图”或“字典”或“哈希表”一样:

> foo = vector()
> foo['CO'] = 'Columbia'
> foo['CO']
        CO 
"Columbia"

假设我有一个数据框country_codes,有两列'A2'和'COUNTRY':

> head(country_codes)
      A2        COUNTRY
1     AF    Afghanistan
2     AL        Albania
3     DZ        Algeria
4     AS American Samoa
5     AD        Andorra
6     AO         Angola

如何将country_codes数据框转换为foo矢量格式?

我尝试了一些不起作用的东西但是太难看了。我也读了一些相关的问题,但我看不出这些关系。

3 个答案:

答案 0 :(得分:2)

(通过tibble::tribble导入的数据,但对功能不重要)。

country_codes <- tribble(
  ~"A2",      ~"COUNTRY",
  "AF",    "Afghanistan",
  "AL",        "Albania",
  "DZ",        "Algeria",
  "AS", "American Samoa",
  "AD",        "Andorra",
  "AO",         "Angola"
)

country_vector <- with(country_codes, setNames(COUNTRY, A2))

country_vector['AF']
#>            AF 
#> "Afghanistan"

答案 1 :(得分:1)

这就是你要找的东西吗?

foo <- country_codes$COUNTRY 
names(foo) <- country_codes$A2
foo
#          AF               AL               DZ               AS               AD               AO 
#"Afghanistan"        "Albania"        "Algeria" "American_Samoa"        "Andorra"         "Angola" 

# @Parfait suggests
foo <- setNames(country_codes$COUNTRY, country_codes$A2)

答案 2 :(得分:1)

我们也可以使用

with(country_codes, unlist(split(COUNTRY, A2)))
#          AD               AF               AL               AO 
#      "Andorra"    "Afghanistan"        "Albania"         "Angola" 
#              AS               DZ 
# "American Samoa"        "Algeria"