From ggrothendieck at myway.com  Mon Nov 29 16:43:25 2004
From: ggrothendieck at myway.com (Gabor Grothendieck)
Date: Mon Nov 29 16:43:34 2004
Subject: [Rd] Differences between "$" and "[["
References: <6.0.1.1.2.20041129153016.0393fec0@stat4ux.stat.ucl.ac.be>
Message-ID: <loom.20041129T164131-973@post.gmane.org>

Eric Lecoutre <lecoutre <at> stat.ucl.ac.be> writes:

: 
: Hi,
: 
: If I define the following list:
: 
:  > (l<-list("text-align"="right"))
: $"text-align"
: [1] "right"
: 
: I know that I can't use l$text-align, as the parser will find a '-' 
operation.
: If I want (need) to use special names, as "text-align", I have to enclose 
: it between "". So I can use:
: 
: l$"text-align" or l[["text-align"]]
: 
: If now I have the text "text-align" defined in a variable:
: p<-"text-align"
: 
: I can use:
:  > l[[p]]
: [1] "right"
: 
: But I can't use l$p
: 
: where as it is said in the help page that 'x$name' is equivalent to 
: 'x[["name"]]'.
: 
: Anyway I will use "[[" but I dont clearly understand this behavior.

[[ evaluates its right argument and $ does not.  The "..." notation is
just to allow one to specify non-syntactic arguments.  One could
alternately use l$`text-align` .  I think the "..." notation
is a holdover from before `...` was implemented.

Its also possible to define your own class and have $ operate any
way you like on it (although its probably best to stick with
standard behavior and the following is not really recommended):

	l<-list("text-align"="right", a=2)
	class(l) <- c("mylist", "list")
	"$.mylist" <- function(x, idx) { 
	     y <- x[[idx]]
	     if (is.null(y)) x[[eval.parent(parse(text=idx))]] else y
	}
	p <- "text-align"
	l$p # "right"
	l$"text-align" # same
	l$`text-align` # same
	a <- 99
	l$a # 2
	l$"a" # same
	l$`a` # same
	l[["a"]] # same
	l[[a]] # 99


[Rd] Differences between "$" and "[["
Gabor Grothendieck