[R] Is it possible to recursively update a function?

David Winsemius dwinsemius at comcast.net
Fri Mar 5 21:30:55 CET 2010


On Mar 5, 2010, at 11:06 AM, Seeker wrote:

> Thanks for your suggestion, Carl. Actually I am looking for a series
> of functions like these
>
> exp(-x)*.5^x
> exp(-x)*.5^x*(1-.4^x)
> exp(-x)*.5^x*(1-.4^x)*(1-.3^x)
> where(.5,.4,.3...) are from the coming results.

Those are not really functions but rather "expressions". Does this help?

 > tvalues <- c(.5,.4,.3)
 > expr <- substitute(exp(-x)*t1^x*(1-t2^x)*(1-t3^x),
                   list(t1=tvalues[1], t2=tvalues[2], t3=tvalues[3]) )
 > expr
# exp(-x) * 0.5^x * (1 - 0.4^x) * (1 - 0.3^x)

I suppose they could be wrapped up into functions but would need to be  
further wrapped inside eval() or else they will return an expression  
string.

 > tfn <- function(x) eval( substitute(exp(-x)*t1^x*(1-t2^x)*(1-t3^x),
                     list(t1=tvalues[1], t2=tvalues[2],  
t3=tvalues[3]) ) )

 > tfn(.5)
[1] 0.07129393
 > tfn2 <- function(x) exp(-x) * 0.5^x * (1 - 0.4^x) * (1 - 0.3^x)
 >
 > tfn2(.5)
[1] 0.07129393

-- 
David.

>
> I am not sure how to construct such an irregular fucntion vector.
>
> On Mar 4, 6:40 pm, Carl Witthoft <c... at witthoft.com> wrote:
>> My foolish move for this week: I'm going to go way out on a limb and
>> guess what the OP wanted was something like this.
>>
>> i=1, foo = x*exp(-x)
>>
>> i=2, foo= x^2*exp(-x)
>> i=3, foo = x^3*exp(-x)
>> .
>> .
>> .
>>
>> In which case he really should create a vector bar<-rep(na,5) ,
>> and then inside the loop,
>>
>> bar[i]<-x^i*foo(x)
>>
>> Carl
>>
>> quoted material:
>> Date: Thu, 04 Mar 2010 11:37:23 -0800 (PST)
>>
>> I need to update posterior dist function upon the coming results and
>> find the posterior mean each time.
>>
>> On Mar 4, 1:31 pm, jim holtman <jholt..._at_gmail.com> wrote:
>>  > What exactly are you trying to do?  'foo' calls 'foo' calls  
>> 'foo' ....
>>  >  How did you expect it to stop the recursive calls?
>>  >
>>  >
>>  >
>>  >
>>  >
>>  > On Thu, Mar 4, 2010 at 2:08 PM, Seeker <zhongm..._at_gmail.com>  
>> wrote:
>>  > > Here is the test code.
>>  >
>>  > > foo<-function(x) exp(-x)
>>  > > for (i in 1:5)
>>  > > {
>>  > > foo<-function(x) foo(x)*x
>>  > > foo(2)
>>  > > }
>>
>> ______________________________________________
>> R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/ 
>> listinfo/r-help
>> PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>
> ______________________________________________
> R-help at 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list