在 R 中使用 dictionaries/lists:如何从键值对中获取值?

Working with dictionaries/lists in R: how to get the values from the key-value pairs?

这与 Working with dictionaries/lists in R 有关,我们在其中尝试使用向量创建一个键值样式的字典,但现在是关于如何访问这些值。

我可以通过以下方式获取钥匙

foo <- c(12, 22, 33)
names(foo) <- c("tic", "tac", "toe")
names(foo)
[1] "tic" "tac" "toe"

我可以访问这些元素

> lapply(FUN=function(a){foo[[a]]},X = 1:length(foo))
[[1]]
[1] 12

[[2]]
[1] 22

[[3]]
[1] 33

然后我可以

unlist(lapply(FUN=function(a){foo[[a]]},X = 1:length(foo)))
[1] 12 22 33
#or 
sapply(FUN=function(a){foo[[a]]},X = 1:length(foo))
[1] 12 22 33

但这很不方便。如何方便地访问 c(12,22,33) 格式的值?在 R 中有现成的方便命令吗?

您已经在 foo 中拥有这些值;他们只有 a names attribute 对数据结构本身没有影响。无论名称如何,任何需要数字向量的函数都可以正常工作。

如果您想删除姓名,只需说:

unname(foo)