RLang: accessing list items via chaining and map (purrr)

Viewed 67

I'm trying R again after a few years, much more used to Python dicts or Kotlin maps or JS objects. I am simply trying the access the value of key-value pairs after using some chaining methods. Unfortunately the normal accessors $ and [[ are not returning the expected values, or throwing errors.

Any idea how to simply get a list of the correct state names ("Alabama", "California", "Arizona") from my sample code? Thank you.

states_list <- list("AL"="Alabama", "AK"="Alaska", "AZ"="Arizona", "CA"="California")  # (etc)
states_hash <- hash("AL"="Alabama", "AK"="Alaska", "AZ"="Arizona", "CA"="California")  # (etc)

"AL-CA-AZ" %>% str_split("-") %>% map(~ states_list$.x)  # NULL 
"AL-CA-AZ" %>% str_split("-") %>% map(~ states_list[.x]) # k-v pairs, not just the values

"AL-CA-AZ" %>% str_split("-") %>% map(~ states_hash$.x)  # NULL 
"AL-CA-AZ" %>% str_split("-") %>% map(~ has.key(.x, states_hash)) # AL:TRUE CA:TRUE AZ:TRUE 
"AL-CA-AZ" %>% str_split("-") %>% map(~ states_hash[.x]) # k-v pairs, not just the values

"AL-CA-AZ" %>% str_split("-") %>% map(~ states_list[[.x]]) # error - "recursive indexing failed at level 2"
"AL-CA-AZ" %>% str_split("-") %>% map(~ states_hash[[.x]]) # error - "wrong arguments for subsetting an environment"

"AL-CA-AZ" %>% str_split("-") %>% states_list[[.x]] # error - "object '.x' not found"
1 Answers

Your problem is really the str_split step. Note that str_split will return a list, rather than a vector. (It does this because you can pass multiple strings to the function at once and it will keep all the results separated in the list.) So when you map over that list, you are just mapping over the single list, not each of three elements in the vector in the list. A somewhat clumsy way to change that is

"AL-CA-AZ" %>% {str_split(., "-")[[1]]} %>% map(~states_list[[.x]])

You can clean it up a bit with purrr:pluck

"AL-CA-AZ" %>% str_split("-") %>% pluck(1) %>% map(~states_list %>% pluck(.x))

Or just do direct indexing for the last step

"AL-CA-AZ" %>% str_split("-") %>% pluck(1) %>% {states_list[.]}
Related