[R] using S4 objects in "with"?

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Wed Sep 26 22:34:46 CEST 2018


On 26/09/2018 4:16 PM, Spencer Graves wrote:
>         Is there anything comparable to "with" for S4 objects?
> 
> 
> EXAMPLE:
> 
> 
>         A "Wave" object in the tuneR package has slots "left" and
> "right", plus others.  I'd like to be able to do something like the
> following:
> 
> 
> library(tuneR)
> x <- seq(0, 2*pi, length = 6)
> all.equal(x, rev(x))
> channel <- round(32000 * sin(440 * x))
> Wobj <- Wave(left = channel, right=rev(channel))
> 
> with(Wobj, quantile(left-right))
> 
> 
>         ** This last statement throws "Error ... object 'left' not found".
> 
> 
>         Is there something comparable to "with" that can do this?

I don't know of anything that is "officially sanctioned".  A couple of 
ideas:

1.  Slots in S4 are stored in attributes.  So

   with(attributes(Wobj), quantile(left - right))

works.  BUT:  as far as I recall, this is an undocumented implementation 
detail, and you aren't supposed to count on it.

2.  You could write an as.list() method for the Wave class, then

   with(as.list(Wobj),

would work.  This may be the "right" way to do this.

Duncan Murdoch




More information about the R-help mailing list