首页 > 解决方案 > RLang:通过链接和映射访问列表项(purrr)

问题描述

几年后我再次尝试 R,更习惯于 Python dicts 或 Kotlin 映射或 JS 对象。我只是在使用一些链接方法后尝试访问键值对的值。不幸的是,普通访问器$[[没有返回预期值,或者抛出错误。

知道如何从我的示例代码中简单地获取正确的州名(“阿拉巴马州”、“加利福尼亚州”、“亚利桑那州”)列表吗?谢谢你。

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"

标签: rpurrrmethod-chaining

解决方案


你的问题真的是str_split一步。请注意,这str_split将返回一个列表,而不是一个向量。(这样做是因为您可以一次将多个字符串传递给函数,它会将所有结果分隔在列表中。)因此,当您map遍历该列表时,您只是映射到单个列表,而不是三个元素中的每一个列表中的向量。一种有点笨拙的改变方法是

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

你可以用它清理一下purrr:pluck

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

或者只是对最后一步进行直接索引

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

推荐阅读