Oleksandr Dyklevych
2010-Dec-09 16:59 UTC
[R] Dynamically build functional expression and taking derivative
Hi! I'm faced the next problem: suppose I have a vector of some coefficient and for some purpose from these coefficients I need dynamically build a functional expression (because, the number of elements in the vector of coefficients might differ each time). So, I'm trying to do like this (let the number of coefficients be 3): Building expression> foo <- gsub(",","*",toString(paste('(p',1:3,'*x + > (1-p',1:3,'))',sep=""))) > foo[1] "(p1*x + (1-p1))* (p2*x + (1-p2))* (p3*x + (1-p3))" But now, how can I take derivative of this expression w.r.t. "x"?> dfoo <- D(foo,"x") #doesn't work as well as > dfoo <- D(as.expression(foo),"x")May be there are other ways to handle this kind of situation? Best regards, Oleksandr
Henrique Dallazuanna
2010-Dec-09 17:46 UTC
[R] Dynamically build functional expression and taking derivative
Try this: D(parse(text = foo), "x") On Thu, Dec 9, 2010 at 2:59 PM, Oleksandr Dyklevych <diklevich@gmail.com>wrote:> Hi! > > I'm faced the next problem: > suppose I have a vector of some coefficient and for some purpose from these > coefficients I need dynamically build a functional expression (because, the > number of elements in the vector of coefficients might differ each time). > So, I'm trying to do like this (let the number of coefficients be 3): > > Building expression > >> foo <- gsub(",","*",toString(paste('(p',1:3,'*x + (1-p',1:3,'))',sep=""))) >> foo >> > [1] "(p1*x + (1-p1))* (p2*x + (1-p2))* (p3*x + (1-p3))" > > But now, how can I take derivative of this expression w.r.t. "x"? > > dfoo <- D(foo,"x") #doesn't work as well as >> dfoo <- D(as.expression(foo),"x") >> > > May be there are other ways to handle this kind of situation? > > > Best regards, > Oleksandr > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]