[R] D function

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun Sep 17 12:36:44 CEST 2000


Douglas Bates <bates at stat.wisc.edu> writes:

> Erin Hodgess <hodgess at uhddx01.dt.uh.edu> writes:
> 
> > Suppose I put in the following:
> > 
> > > w1 <- expression(2*x)
> > > v1 <- expression(x^2)
> > 
> > and I want to get the derivative of w1 * v1 with respect to x
> > > D(w1*v1,"x")
> > Error in w1 * v1 : non-numeric argument to binary operator
> > Is there a way around this, please?
> 
> You need to create a single expression that does not refer to w1 and
> v1.
> 
> > D(expression((2 * x) * (x * 2)), "x")
> 2 * (x * 2) + (2 * x) * 2

...which you can do from the constituent parts as follows:

> w1<-quote(2*x)
> v1<-quote(x^2)
> call("*",v1,w1)
x^2 * 2 * x
> D(call("*",v1,w1),"x")
2 * x * (2 * x) + x^2 * 2

Notice that you need to make the subexpressions mode "call" rather
than "expression" in order to be able to stick them together woth
call. 

One word of warning. This stuff bypasses the parser and the deparser
in R does not insert parentheses when necessary, hence:

> w1<-quote(2+x)
> v1<-quote(x)
> call("*",v1,w1)
x * 2 + x
> D(call("*",v1,w1),"x")
2 + x + x

(One "nice little" exercise is to fix the deparser so that it
auto-parenthesizes, and at the same time get the parser to delete them
in input)

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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