# Re: [R] Function (x) as consecutive values

From: Paul Chatfield <paulosdoulos_at_yahoo.co.uk>
Date: Thu 18 May 2006 - 18:12:45 EST

x<-1:4
trial<- function(x)
{xx<-matrix(runif(20), 2, 10)
if (xx[1,x]<0.5) { ...}

Thanks

Paul

Jacques VESLOT <jacques.veslot@good.ibl.fr> wrote:   ?cumsum

> system.time({ z <- NULL ; for (i in 1:1000) z <- c(z, sum((1:i)**2)) })
[1] 0.04 0.00 0.04 NA NA
> system.time( zz <- cumsum((1:1000)**2) )
[1] 0 0 0 NA NA
> all.equal(z,zz)
[1] TRUE

Jacques VESLOT

CNRS UMR 8090
I.B.L (2ème étage)
1 rue du Professeur Calmette
B.P. 245
59019 Lille Cedex

Tel : 33 (0)3.20.87.10.44
Fax : 33 (0)3.20.87.10.31

Paul Chatfield a écrit :
> Hi - I'm trying to avoid using a 'for' loop due to inefficiency and instead use a function (and ultimately tapply as I'm working on a matrix) but I can't figure out how to get 'function' to take the variables as anything other than vectors for example
>
> aa<-0
> x<-1:4
> test.fun<-function(x)
> {aa<-(x*x +aa)
> return(aa)}
> test.fun(1:4)
>
> This code returns 'aa' as 1 4 9 16, but I'd like it to return aa as 1 5 14 30 taking into consideration that I've just calculated aa for x=1. Aside from using loops, is there not a simple way of telling R to work out x for consecutive values?
>
> thanks
>
> Paul Chatfield
>
>

> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help