[R] ?max (so far...)

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jul 2 12:58:14 CEST 2009


On 01/07/2009 9:10 PM, Carl Witthoft wrote:
>  > More generally, you can always write a loop.  They aren't necesssrily 
> fast
>  > or elegant, but they're pretty general.  For example, to calculate 
> the max
>  > of the previous 50 observations (or fewer near the start of a 
> vector), you
>  > could do
>  >
>  > x <- ... some vector ...
>  >
>  > result <- numeric(length(x))
>  > for (i in seq_along(x)) {
>  >  result[i] <- max( x[ max(1, i-49):i ])
>  > }
>  >
>  > Duncan Murdoch
>  >
> 
> You should be able to do the same as that loop with one of the *apply 
> functions as well, which would be cleaner and faster (usually).
> 
> Something like (this isn't real code and won't work)
> 
> x<-lapply(function(i,j) max(foo[i:j]), seq(1,N-50),seq(50,N))
> (where foo is your original vector of length N)

The advantage of the explicit loop is that it's usually easy to get it 
to work, and to recognize that it does work.  I think people should use 
explicit loops more, apply-like functions less.  Clarity matters.  Speed 
sometimes matters, but more often in terms of "when will I get this to 
work?" than in terms of "when will this finish running?".

Duncan Murdoch




More information about the R-help mailing list