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

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


Thanks for your reply, though this still wouldn't work with a function for example, starting code like below fails because x is read as a vector as opposed to doing it for x=1 then x=2 - is there any way of tweaking the code easily, or do I just resign myself to for loops to do that?    

  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

http://www-good.ibl.fr


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
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>

        [[alternative HTML version deleted]]



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu May 18 18:16:59 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 18 May 2006 - 20:10:13 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.