【发布时间】:2021-04-18 05:01:42
【问题描述】:
几年后我再次尝试 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"
【问题讨论】:
标签: r purrr method-chaining