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

Uwe Ligges ligges at statistik.tu-dortmund.de
Fri Mar 5 17:24:03 CET 2010



On 05.03.2010 01:40, Carl Witthoft 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)

Since in this case foo(x) is independent of i, you are wasting 
resources. Moreover you could calculate it for a whole matrix at once. 
Say you want to calculate this for i=1, ..., n with n=5 for some (here 
pseudo random x), then you could do it simpler after defining some data 
as in:

set.seed(123)
x <- rnorm(10)
n <- 5


using the single and probably most efficient line:

  outer(x, 1:n, "^") * exp(-x)

or if x is a length 1 vector then even simpler:

set.seed(123)
x <- rnorm(1)
n <- 5

  x^(1:5) * exp(-x)

But we still do not know if this is really the question ...

Uwe Ligges



>
> 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-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.



More information about the R-help mailing list