[R] Basic Question on Keys/Values

Douglas Bates bates at stat.wisc.edu
Mon Jun 9 20:07:58 CEST 2008


On Mon, Jun 9, 2008 at 12:55 PM, Dumblauskas, Jerry
<jerry.dumblauskas at credit-suisse.com> wrote:
> As a java programmer, I'm having issue conceptualizing the following use
> case:

> Given an value, passed into a function, how do I pull out the lookup?

> Ie.
> A list of keys (key1, key2, key3)
> A list of values (val1,val2,val3)

> I want to write a function (or is there something built in?) such that

> Callit <- (thekey) {
> (magic happens here)
> Return value
> }

If the keys are text strings then you can use a named list as the container.

> foo <- list(a = 1:10, b = LETTERS[1:3], ttt = Formaldehyde)
> foo$b
[1] "A" "B" "C"
> bar <- "a"
> foo$bar
NULL
> foo[[bar]]
 [1]  1  2  3  4  5  6  7  8  9 10

Note that the $ operator is an extractor for an explicit name.  If you
want the value corresponding to a key which is itself stored as an
object in R you must use the '[[' notation.

Lists are suitable for a small to moderate number of key/value pairs.
For large numbers of key/value pairs you may want to consider
environments instead.

> Any ideas?
>
> Thanks a bunch!
>
> ==============================================================================
> Please access the attached hyperlink for an important electronic communications disclaimer:
>
> http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html
> ==============================================================================
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list