Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data frame columns to a vector that is like a dictionary

Tags:

dataframe

r

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.

like image 976
dfrankow Avatar asked Dec 06 '25 05:12

dfrankow


2 Answers

(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"
like image 97
Jonathan Carroll Avatar answered Dec 07 '25 20:12

Jonathan Carroll


We can also use

with(country_codes, unlist(split(COUNTRY, A2)))
#          AD               AF               AL               AO 
#      "Andorra"    "Afghanistan"        "Albania"         "Angola" 
#              AS               DZ 
# "American Samoa"        "Algeria" 
like image 32
akrun Avatar answered Dec 07 '25 20:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!