[R] Function (x) as consecutive values
Jacques VESLOT
jacques.veslot at good.ibl.fr
Thu May 18 10:52:52 CEST 2006
sorry, don't understand your problem...
i think it's better to use matrices directly or faster funtions;
but sapply(1:4, function(x) ...) can do the job easily instead of 'for' loops.
-------------------------------------------------------------------
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 :
> 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 at 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
> >
> >
> > Send instant messages to your online friends
> http://uk.messenger.yahoo.com
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at 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
> >
>
>
> Send instant messages to your online friends http://uk.messenger.yahoo.com
>
More information about the R-help
mailing list