Re: [R] Defining binary indexing operators

From: Tony Plate <tplate_at_acm.org>
Date: Thu 28 Apr 2005 - 08:46:29 EST

It's not necessary to be that complicated, is it? AFAIK, the '$' operator is treated specially by the parser so that its RHS is treated as a string, not a variable name. Hence, a method for "$" can just take the indexing argument directly as given -- no need for any fancy language tricks (eval(), etc.)

 > x <- structure(3, class = "myclass")
 > y <- 5
 > foo <- function(x,y) paste(x, " indexed by '", y, "'", sep="")
 > foo(x, y)

[1] "3 indexed by '5'"
 > "$.myclass" <- foo
 > x$y
[1] "3 indexed by 'y'"
 >

The point of the above example is that foo(x,y) behaves differently from x$y even when both call the same function: foo(x,y) uses the value of the variable 'y', whereas x$y uses the string "y". This is as desired for an indexing operator "$".

Gabor Grothendieck wrote:
> On 4/27/05, Ali - <saveez@hotmail.com> wrote:
>

>>Assume we have a function like:
>>
>>foo <- function(x, y)
>>
>>how is it possible to define a binary indexing operator, denoted by $, so
>>that
>>
>>x$y
>>
>>functions the same as
>>
>>foo(x, y)

>
>
> Here is an example. Note that $ does not evaluate y so you have
> to do it yourself:
>
> x <- structure(3, class = "myclass")
> y <- 5
> foo <- function(x,y) x+y
> "$.myclass" <- function(x, i) { i <- eval.parent(parse(text=i)); foo(x, i) }
> x$y # structure(8, class = "myclass")
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Apr 28 08:50:25 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:27 EST