Re: [R] Basic Question on Keys/Values

From: Douglas Bates <bates_at_stat.wisc.edu>
Date: Mon, 09 Jun 2008 13:07:58 -0500

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.
>



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. Received on Mon 09 Jun 2008 - 18:46:25 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 09 Jun 2008 - 19:30:37 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive