[R] substitute, eval and hastables
Uwe Ligges
ligges at statistik.uni-dortmund.de
Wed Jan 29 13:14:02 CET 2003
Serge Boiko wrote:
> I have the following problem. I have an automatically generated named
> list with "stringified" names:
>
> a <- list("A"=..., "B"=..., "C"=..., )
>
> then I want to refer to the elements of the list, stored as an vector
> of names:
>
> nn <- c("A", "B", "C"), so that I could get list elements like
>
> a$nn[1], a$nn[2], etc. Obviously it doesn't work. Instead I do:
a$nn is evaluated at first, which looks for a list element called "nn"!
It's the convinient form for a[["nn"]].
> nn.Exp <- substitute(expression(a$b), list(b=nn[1]))
> eval(nn.Exp)
That's an enormous *overhead*. To construct such an expression, I'd try
(given here just for fun):
nn.Exp <- substitute(a$b, list(b=nn[1]))
eval(nn.Exp)
> in a result I get
> expession(a$"A") but not the value stored in the list.
> Meanwhile if I manually construct expression as expression(a$"A") and
> then evaluate it, it works fine.
>
> How do I solve that problem? Perhaps using such a list with
> "stringified" names are not very good programming style, but this is
> convenient to store and retrieve elements if list should be filled
> automatically from numerous sources. In this way I'm trying to emulate
> a hash-table behavior. Perhaps there is a better way?
>
> Any help is highly appreciated
Use the more general [[ ]] indexing mechanism for lists as in:
a[[nn[1]]]
a[[nn[2]]]
See "An Introduction to R" or any book on the S language for more
details regarding indexing.
Uwe Ligges
More information about the R-help
mailing list