[R] Trouble with compound functions---differential equations

Rolf Turner rolf.turner at xtra.co.nz
Thu Jun 16 05:30:22 CEST 2011


On 16/06/11 11:07, Aimee Jones wrote:
> Hi all,
> My apologies if this message is incredibly inept but I am very new to both
> computer programming and to R.
>
> I am working with the odesolve add-on and have the following function
> defined
>
> RVF_Single<- function(t, x, p)
> within the script I also have the following functions defined:
>
> T1<-function(t) {T1<-27.5-12.5*cos(2*pi*t/365)}
> and
>
> B1<-function(T1,t) {B1<-dnorm(T1(t),mean=22.5,sd=3.3)}

     Actually your code should read:

T1<-function(t) {27.5-12.5*cos(2*pi*t/365)}

and

B1<-function(T1,t) {dnorm(T1(t),mean=22.5,sd=3.3)}

i.e. don't assign the value that you calculate in the code; this
is the value ***returned*** by the function.  What you is in effect
harmless here, but it is confusing and could cause problems in
other contexts.
> When the script is run it doesn't return an error message but the graphs
> returned are "wrong". When I input "plot(T1,0,3650)" it returns the plot of
> T1 as expected---a series of waves between 15 and 40, BUT when I input
> "plot(B1,0,3650)" I get an error message of "Error in 2 * pi * t : 't' is
> missing".
>
> Can anyone advise as to why t registers for function T1 but disappears for
> function B1?

Well, T1() a function of ***t*** only (where t is the variable against which
you expect the values of T1() to be plotted.  Whereas, B1 is a function of
two variables T1 and t, which confuses things.

Note that by calling plot() in this way you are in fact calling 
plot.function()
which is in fact a wrapper for curve().  As has been discussed recently on
this list, the syntax for curve() is a bit delicate.

A workaround for your problem is:

     plot(function(t){B1(T1,t)},0,3650)

HTH

     cheers,

         Rolf Turner



More information about the R-help mailing list