s-news
[Top] [All Lists]

vectorizing a function

To: <s-news@lists.biostat.wustl.edu>
Subject: vectorizing a function
From: "Leeds, Mark" <mleeds@mlp.com>
Date: Fri, 29 Oct 2004 18:34:49 -0400
Cc: <cspark@clemson.edu>
Thread-index: AcS+B4ADmDLZcXJFQb67Y1mPKiZTdA==
Thread-topic: vectorizing a function
i sent out a question
about vectorizing a function
a few days ago. the solution
that was posted ( using pmin instead of min ) 
is appreciated and
gets close to what i want but it doesn't
quite work because of the
recursive nature of what
i want to do. the cumprod part
of the solution just accumulates the product
blindly regardless of the condition
so that what makes it not quite work.
 
if anyone knows the filter function
well enough to use it to avoid the loop,
or any other way, the knowledge would be
appreciated.
 
the original function is deceptively recursive
and may not be as simple as it
looks when trying to avoid looping.
 
 
                                    thanks
 
                                    mark
 
 
the looping version of the function
and the almost solution
are given below for people ( like me )
who deleted the original email.
 
--------------------------------------------------------------
 
originalfunction<-function(invector)
 
outvector<-invector
 
for ( i in 2:length(invector) ) {
 
if  ( invector[i] < 1 ) {
 
outvector[i]_invector[i]*outvector[i-1]
 
}
 
 
return(outvector)
 
-------------------------------------------------------------------
 
almostworks<-function(invector) {
 
outvector<-invector
part<-cumprod(pmin(invector,1))
outvector[invector < 1]<-part[invector < 1]
 
return(outvector)
 
-------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
<Prev in Thread] Current Thread [Next in Thread>