[R] lapply() reccursively

Charles C. Berry cberry at tajo.ucsd.edu
Tue Oct 13 18:42:03 CEST 2009


On Tue, 13 Oct 2009, Kaveh Vakili wrote:

>
> Hi all,
>
> I was wondering whether it is possible to use the lapply() function
> to alter the value of the input, something in the spirit of :
>
> a1<-runif(100)
> a2<-function(i){
> a1[i]<-a1[i-1]*a1[i];a1[i]
> }
> a3<-lapply(2:100,a2)
>
> Something akin to a for() loop, but using the lapply() infrastructure.
> I haven't been able to get rapply() to do this.

Maybe you want to check out

 	?Reduce

For the example above, something like

a3 <-  Reduce( "*", a1, accumulate = TRUE )


HTH,

Chuck

>
> The reason is that the "real" a2 function is a difficult function that only needs to be evaluated if the value of a1[i-1] meets some criteria.
>
> Thanks in advance,
>
> ______________________________________________
> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901




More information about the R-help mailing list