[R] Arguments to "personalised" plot()
Rolf Turner
r.turner at auckland.ac.nz
Sun Oct 7 23:51:29 CEST 2007
On 8/10/2007, at 10:01 AM, Deepayan Sarkar wrote:
> On 10/7/07, Ted Harding <Ted.Harding at manchester.ac.uk> wrote:
>> Hi Folks,
>>
>> I'm curious for an explanation of the following -- it's a
>> matter of trying to understand how R parses it.
>>
>> I've written sundry little "helper" variants of functions,
>> in particular plot(), to save repetitively typing the same
>> options over and over again.
>>
>> For example:
>>
>> plotb <- function(x,...){plot(x,pch="+",col="blue",...)}
>>
>> This does exactly what you'd expect it to do when fed with
>> a vector of values to plot, e.g.
>>
>> plotb(cos(0.01*2*pi*(0:100)))
>>
>> namely a plot of the values of cos(..) with x-coordinates
>> marked 0, 20, 40, 60, 80, 100, as blue "+".
>>
>> As expected, one can add other plot options if needed, e.g.
>>
>> plotb(cos(0.01*2*pi*(0:100)), xlim=c(0,4*pi))
>>
>> if one wants. In this case, I'm supposing that the "xlim=c(0,4*pi)"
>> goes in under the umbrella of "...", which is what I guessed
>> would happen.
>>
>> Interestingly, though, if I do
>>
>> x<-0.01*2*pi*(0:100); plotb(x,cos(x))
>>
>> I now get it with the x-axis labelled 0,1,2,3,4,5,6 just as
>> if I had used the built-in
>>
>> x<-0.01*2*pi*(0:100); plot(x,cos(x),pch="+",col="blue")
>>
>> and I can *also* add "xlim=c(0,4*pi)":
>>
>> x<-0.01*2*pi*(0:100); plotb(x,cos(x),xlim=c(0,4*pi))
>>
>> and it still works! Now the latter is the same "..." mechanism
>> as before, I suppose; but this doesn't explain how plotb()
>> "sees" x, along with cos(x), and picks it up to do the
>> right thing.
>>
>> So my question -- which is why I'm posting -- is:
>>
>> How does "x" get in along with "cos(x)" when I do
>> "plotb(x,cos(x))", when the definition of the function is
>>
>> plotb <- function(x,...){plot(x,pch="+",col="blue",...)}
>
> I'm not sure exactly which part you didn't expect. Given this
> definition of plotb, I would expect
>
> plotb(x,cos(x))
>
> to expand to
>
> plot(x, pch="+", col="blue", cos(x))
>
> and as far as I can tell, these give identical results. Is that what
> surprises you? Why?
>
> The other possibility is that you are surprised by the behavior of
>
> plot(x, pch="+", col="blue", cos(x))
>
> Remember that named arguments trump positional matching, and
> consequently, this is equivalent to
>
> plot(x, cos(x), pch="+", col="blue")
I think that this is the crucial issue. I'm guessing that what
puzzled Ted (it is what
certainly puzzled me) was ``how did plot() know that cos(x) was the
y-value?''
Your (very well expressed) explanation makes this clear.
cheers,
Rolf Turner
######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
More information about the R-help
mailing list