21

In R, I have, for example:

> foo <- list(a=1,b=2,c=3)

If I type foo, I get:

$a
[1] 1

$b
[1] 2

$c
[1] 3

How can I look through foo to get a list of "keys" only? In this case, (a, b, c).

earl
  • 40,327
  • 6
  • 58
  • 59

2 Answers2

21

An R list can have named elements and so function as a dictionary structure. You can just do:

> names(foo)
[1] "a" "b" "c"

If you are looking for a dictionary structure you might also consider using the hash packages which provides a Python and Perl like dictionary/hash with the expected functions such as keys, so you can say:

keys(hash)

In terms of performance a list serves as a better dictionary than a hash for several hundred elements or fewer (<200) because of the cost of the hashing. The hash package is much better for very large dictionaries.

ctbrown
  • 2,271
  • 17
  • 24
15
> names(foo)
[1] "a" "b" "c"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418