[R] symbolic manipulations

Thomas Lumley tlumley at u.washington.edu
Sat Apr 7 02:07:29 CEST 2001


On Fri, 6 Apr 2001, Jeff Miller wrote:

>
>
> Hi All,
>
>
>     I copied code from an Splus manual to take symbolic derivatives:
>
>             my.deriv <- function( mathfunc, var )
>                         {
>                             tmp <- substitute(mathfunc)
>                             name <- deparse(substitute(var))
>                             D(tmp,  name)
>                           }
>
>         (The code also works in R).
>
>
>         When I try this on  x^2  I  get
>
>         > my.deriv(x^2,  x)
>         2 * x
>
>         Suppose I assign the output of  my.deriv(x^2,  x)  to deriv.xsqr :
>
>         > deriv.xsqr   <-   my.deriv(x^2,   x)
>         > deriv.xsqr
>         2 * x
>         >
>
>         My question is, how do I take the derivative of  deriv.xsqr
>         (I want the answer to be 2) ?

FAQ 7.6 explains that this is precisely why the D() function doesn't work
like my.deriv().

You can do it with
R> eval(substitute(my.deriv(expr,x),list(expr=deriv.xsqr)))
 [1] 2

but this is making life unnecessarily difficult for yourself.

R> D(D(expression(x^2),"x"),"x")
 [1] 2

is easier

	-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list