Key-Value mapping in R

406 Views Asked by At

I would like to categorize the cities in city_1, city_2 etc in my dataset.. but using a key value mapping. For example I would like to retrieve "city_1" giving 4059 as value and so on..

Do you have some suggestions on how can I solve this? Thank you!

This is the list:

zip_codes <- list("city_1" =c(4000, 4001, 4005, 4009, 4010, 4018, 4019, 4020, 4030, 4031, 4051, 4052, 4053, 4054, 4055, 4056, 4057, 4058, 4059))
|__A____|___B___|
|__4000_|_city_1|
|__4009_|_city_1|
|__4059_|_city_1|
|__4059_|_city_1|
|__4565_|_city_2|

So for example, I have a dataset, in which zip codes such as the ones above appear in the columns and I would like to map to which place each of those zip_code belongs. I want to make column "B" from the zip code list. I was thinking to a key-values mapping, but maybe in R it is not the best way....Do you have better ideas?

3

There are 3 best solutions below

3
akrun On

We can use enframe from tidyverse

 library(tibble)
 library(dplyr)
 ref_df <- enframe(zip_codes) %>%
             unnest(c(value))

and then we can extract with

as.character(ref_df$name[ref_df$value == 4059])
0
Ronak Shah On

We can create a key-value pair dataframe from the list using stack.

ref_df <- stack(zip_codes)

and then it is easy to extract any city name using the zip code.

as.character(ref_df$ind[ref_df$values == 4059])
#[1] "city_1"
0
user2554330 On

If you really want key-value pairs, then you can do it with a named vector. For example,

df <- data.frame(A = c(4000, 4009, 4059, 4565), 
                 B = c("city_1", "city_1", "city_1", "city_2"),
                 stringsAsFactors = FALSE)

keyvalue <- df$B
names(keyvalue) <- df$A

# Look up 4059:

keyvalue[as.character(4059)]
#>     4059 
#> "city_1"

Note that your original table has 4059 in it twice. This solution assumes that was a typo: you shouldn't have the same code more than once. I'm not even sure what that would mean in terms of your original problem.