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

Carl Witthoft carl at witthoft.com
Thu Jul 2 03:10:04 CEST 2009


 > 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)


Carl




More information about the R-help mailing list