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

时光怂恿深爱的人放手 提交于 2020-01-03 05:02:19

问题


This is related to Working with dictionaries/lists in R, where we try to create a key-value style dictionary with vectors, but now about how to access the values.

I can get the keys in the following way

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

and I can access the elements

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

[[2]]
[1] 22

[[3]]
[1] 33

and then I can do

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

but this is very inconvenient. How can I conveniently access the values in the format c(12,22,33)? Is there some ready convenient command for this in R?


回答1:


You already have these values in foo; they only have a names attribute which has no impact on the data structure itself. Any function expecting a numeric vector will work perfectly fine, regardless of the names.

If you want to remove the names, just say:

unname(foo)


来源:https://stackoverflow.com/questions/45460273/working-with-dictionaries-lists-in-r-how-to-get-the-values-from-the-key-value-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!