hhh
hhh

Reputation: 52840

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

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?

Upvotes: 0

Views: 2035

Answers (1)

Calimo
Calimo

Reputation: 7959

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)

Upvotes: 1

Related Questions