Re: [R] avoiding a loop

From: Jerome Asselin <jerome.asselin_at_crchum.qc.ca>
Date: Tue 24 Oct 2006 - 18:53:54 GMT

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

______________________________________________
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
and provide commented, minimal, self-contained, reproducible code.
Received on Wed Oct 25 04:58:11 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 Tue 24 Oct 2006 - 20:30:35 GMT.

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