[R] Plotting several functions in the same display (again)

Duncan Murdoch murdoch.duncan at gmail.com
Thu Apr 4 19:07:02 CEST 2013


On 04/04/2013 11:38 AM, Julio Sergio wrote:
> To superimpose two functions plots in the same page. The functions L0
> and L1, as defined below, I use the following code:
>
>    # An accumulative normal distribution function with
>    # several parametres
>    f0 <- function(mu, xm, ds, n) {
>      1 - pnorm((xm-mu)/(ds/sqrt(n)))
>    }
>
>    f1 <- function(mu,n) f0(mu, 386.8, 48, n)
>
>    # Two functions with just the parameter mu
>    L0 <- function(mu) f1(mu, 36)
>    L1 <- function(mu) f1(mu,100)
>    plot(L0,ylim=c(0,1),xlim=c(360,420))
>    curve(L1,add=T)
>
> However, I'm puzzled with a problem in the same line: When I passed a
> "function producer" to plot, again it worked well; however it didn't work in
> the same way when trying to use this same argument in curve. See what I'm
> talking about:
>
>    # A particular normal distribution function:
>    dn8 <- function(z,m) dnorm(z,m,8) #  norm dist with sd=8
>
>    # A function that produces functions:
>    #   returns a function such that given a mean(i) depends only
>    #   on z
>    fi <- function(i) function(z) dn8(z,i)
>
>    plot(fi(370),xlim=c(360,420)) # Works well!
>
>    curve(fi(380),add=T) # This doesn't work
>
>    # However, if I put it in this way, surprisingly, it works!
>    ff <- fi(380)
>    curve(ff,add=T)
>
> I cannot understand this behaviour. Could anyone give me some feedback on
> this?

The curve() function is trying to be clever, but it's not.  You can 
probably get what you want using curve(fi(380)(x), add=TRUE).  It treats 
the "x" argument specially.

Duncan Murdoch



More information about the R-help mailing list