Thu Jul 12 15:56:30 CEST 2007

```How about

revLag <- function(x, shift=1) rev( Lag(rev(x), shift) )

x <- 1:5
revLag(x, shift=2)

As a matter of fact, here is a generalized version of Lag to include
negative shifts.

myLag <- function (x, shift = 1){

xLen <- length(x)
ret <- as.vector(character(xLen), mode = storage.mode(x))
attrib <- attributes(x)
if (!is.null(attrib\$label))
atr\$label <- paste(attrib\$label, "lagged", shift, "observations")

if (shift == 0) return(x)

if( xLen <= abs(shift) ) return(ret)

if (shift < 0) x <- rev(x)
retrange = 1:abs(shift)
ret[-retrange] <- x[1:(xLen - abs(shift))]
if (shift < 0) ret <- rev(ret)

attributes(ret) <- attrib
return(ret)
}

and some test examples:

myLag(1:5, shift=2)
 NA NA  1  2  3

myLag(letters[1:4], shift=2)
 ""  ""  "a" "b"

myLag(factor(letters[1:4]), shift=2)
 <NA> <NA> a    b
Levels: a b c d

myLag(1:5, shift=-2)
  3  4  5 NA NA

myLag(letters[1:4], shift=-2)
 "c" "d" ""  ""

myLag(factor(letters[1:4]), shift=-2)
 c    d    <NA> <NA>
Levels: a b c d

Aydemir, Zava (FID) wrote:
> Hi,
>
> is there any function in R that shifts elements of a vector to the
> opposite direction of what Lag()  of the Hmisc package does? (something
> like, Lag(x, shift = -1) )
>
> Thanks
>
> Zava
> --------------------------------------------------------
>
> This is not an offer (or solicitation of an offer) to buy/se...{{dropped}}
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help