r - 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"
解决方案
你的问题真的是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[.]}
推荐阅读
- python - 如何在python中调用输入的数据类型
- emacs - Magit:更改差异中文件名的颜色
- python - Python - 与进程一起使用时,共享内存的大小默认为默认大小
- flutter - 带浏览量的 Navigator 2.0
- angular - 使用角度路由器实现简单的后退导航
- java - 使用 ConstraintValidator 使用拖曳类型进行自定义 bean 验证
- arrays - char数组和指向char数组的指针之间的区别
- reactjs - 开玩笑测试 useInterval React Hook 不起作用
- neural-network - 如何求 LSTM 神经网络嵌入层的神经元个数?
- python - 连接 3 个“功能”而不是分开保存