[R] avoiding a loop
Leeds, Mark (IED)
Mark.Leeds at morganstanley.com
Tue Oct 24 21:06:40 CEST 2006
I appreciate your effort but I'm fairly certain that won't work. The
loop I have written is pseudo "recursive" in the sense that
outvector depends on its previous value and this previous value may have
changed because it depnds on the previous value of itself.
The fact that there is no outvector on the right side of your last line
of code tells me that it's probably not what I want. I'll
Try it though. It can't hurt. I do appreciate the help.
-----Original Message-----
From: Jerome Asselin [mailto:jerome.asselin at crchum.qc.ca]
Sent: Tuesday, October 24, 2006 2:54 PM
To: Leeds, Mark (IED)
Cc: R-help at stat.math.ethz.ch
Subject: Re: [R] avoiding a loop
On Tue, 2006-10-24 at 14:36 -0400, Leeds, Mark (IED) wrote:
> I think I asked a similar question 3 years ago to the Splus list and
> I think the answer was no or noone answered so noone should spend more
> than 5 minutes on this because it could definitely be a waste of time.
>
> My question is whether the function below can be rewritten without a
> for loop. apply is fine if it can be done that way but i doubt it. I
> call it a lot and would prefer to not loop.
>
> #---------------------------------------------------------------------
> --
> --------------------------
>
> constructLt<-function(invector) {
>
> outvector<-invector
>
> for ( i in 2:length(invector) ) {
> if ( invector[i] < 1 ) {
> outvector[i]<-invector[i]*outvector[i-1]
> }
> }
>
> return(outvector)
>
> }
You sure can vectorize this. Try this below... I haven't tested, but it
should be close to your solution. There's also
a <- invector[-1]
outvector <- invector
wh <- which(a<1)+1
outvector[wh] <- a[wh] * invector[-length(invector)][wh-1] outvector
HTH,
Jerome
--
Jerome Asselin, M.Sc., Agent de recherche, RHCE CHUM -- Centre de
recherche
3875 rue St-Urbain, 3e etage // Montreal QC H2W 1V1
Tel.: 514-890-8000 Poste 15914; Fax: 514-412-7106
--------------------------------------------------------
This is not an offer (or solicitation of an offer) to buy/se...{{dropped}}
More information about the R-help
mailing list