In R, a vector can act like what some languages call a "map" or "dictionary" or "hash table":
> foo = vector()
> foo['CO'] = 'Columbia'
> foo['CO']
CO
"Columbia"
Suppose I have a data frame country_codes, with two columns 'A2' and '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
How do I get the country_codes data frame into the foo vector format?
I tried a few things that didn't work but are too ugly to post here. I also read some of the related questions, but I couldn't see the relations.
(data imported via tibble::tribble, but not essential to the functionality).
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"
We can also use
with(country_codes, unlist(split(COUNTRY, A2)))
# AD AF AL AO
# "Andorra" "Afghanistan" "Albania" "Angola"
# AS DZ
# "American Samoa" "Algeria"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With