Re: [R] Defining binary indexing operators

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Thu 28 Apr 2005 - 11:07:54 EST

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")
>
> what about this approach:
>
> foo <- function(x, y) x+y
> assign("$", foo)
>
> would this overwrite $

 Yes.
 and make R to forget its definitions in the global environment?
 Yes.
 Your construct might still be used in a local environment.  f <- function(x,y) {
 "$" <- function(x,y) x+y
 x$y
}
f(1,2) # 3
 # or
z <- local({
 "$" <- function(x,y) x+y
 x <- y <- 3
 x$y
})
z # 6
 works and outside of f and the local, $ works normally.

        [[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 Received on Thu Apr 28 11:13:36 2005

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