0

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?

hhh
  • 50,788
  • 62
  • 179
  • 282
  • I assume you meant 12, not 11? – Calimo Aug 02 '17 at 12:04
  • @Calimo yes, fixed, thank you. – hhh Aug 02 '17 at 12:05
  • I am not sure what you are asking. Do you mean `foo[1]` or `foo["tic"]`? your final function could be written `unlist(lapply(FUN=function(a){foo[a]},X = 1:length(foo)))` or more simply as `sapply(FUN=function(a){a, X = foo)`. – lmo Aug 02 '17 at 12:14
  • @Imo Calimo already answered probably with the most simplest solution. I did not know the function `unname` that perfectly works here. Thank you Calimo. – hhh Aug 02 '17 at 12:15

1 Answers1

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)
Calimo
  • 7,510
  • 4
  • 39
  • 61