Skip to content

Defining binary indexing operators

8 messages · Gabor Grothendieck, Tony Plate, Ali -

#
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)
#
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 "$".

-- Tony Plate
Gabor Grothendieck wrote:
#
what about this approach:

foo <- function(x, y) x+y
assign("$", foo)

would this overwrite $ and make R to forget its definitions in the global 
environment?
#
Excuse me!  I misunderstood the question, and indeed, it is necessary be 
that complicated when you try to make x$y behave the same as foo(x,y), 
rather than foo(x,"y") (doing the former would be inadvisible, as I 
think someelse pointed out too.)
Tony Plate wrote:
#
If I got it right, in the above example you provided '$' is defined as a 
method for a S3 class. How is it possible to do the same with a S4 class. If 
this is not possible, what is the best way to define the '$' operator whose 
first arguments is a S4 object and doesn't overwrite the global definition?