Re: [Rd] Problem calling $ inside a $ method

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Tue, 08 May 2007 08:23:46 +0200

Seth Falcon wrote:
> Hello,
>
> I wonder if this will make it through the spam filters given the
> subject line.
>
> I'm seeing the following when trying to call a dollar method inside of
> a dollar method.
>
>
> setClass("Foo", representation(d="list"))
> [1] "Foo"
>
> f <- new("Foo", d=list(bob=1, alice=2))
>
> ## We can call dollar at this level and it works as expected
>
> `$`(f, "bo")
> [1] 1
>
> `$`(f, "al")
> [1] 2
>
`$`(f_at_d, "bo"), surely.
> ## So set a method on Foo that does this
>
> setMethod("$", "Foo", function(x, name) `$`(x_at_d, name))
> [1] "$"
>
> ## But it doesn't work. Why?
>
>
This has nothing to do with methods, it's $'s nonstandard evaluation rules that are doing you in. This doesn't work either

 > x <- "al"
 > `$`(f_at_d, x)
NULL and the reason is that `$`(a,b) is _exactly_ equivalent to a$b insofar as auto-quoting the second argument is concerned
> f$bo
> NULL
>
> f$al
> NULL
>
>

...so both of these look for f_at_d$name which isn't there.
> ## Here is a hackish workaround.
>
> setMethod("$", "Foo", function(x, name)
> eval(substitute(x_at_d$FOO, list(FOO=name))))
> [1] "$"
>
> f$bo
> [1] 1
>
> f$al
> [1] 2
>
> Other suggestions for workarounds? Is this a bug?
>
Not a bug. Another workaround is to use "[[", but beware that Robert has evil intentions with respect to that and partial matching...



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Tue 08 May 2007 - 06:28:33 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 08 May 2007 - 15:03:44 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.