hjw
hjw

Reputation: 1289

Logical vector in R based on previous row

I would like to select a subset of a vector based on the value in the previous row. Is this something that is possible without a loop? More specifically, using time series notation (I made up the 2nd line), I am looking to get y

x = c(-2,3,-1,2,8,)
y = x(t)[x(t)>0, x(t-1)<0, x(t)-x(t-1)>2]
y  
[1] 3

I don't really need a solution for y as I can always loop it. But would be very interested to know if there is a shift operator or something similar for logical vector indexing

Upvotes: 0

Views: 253

Answers (3)

hjw
hjw

Reputation: 1289

This is what I found to accomplish what I would have liked

x = c(-2,3,-1,2,8)
x = zoo(x)
y = x[x>0 & lag(x,-1)<0 & (x-lag(x,-1))>2]
y
2 4 
3 2 

It very elegantly handles lag(x,-i) without you having to resize your vector

Upvotes: 0

Zhenglei
Zhenglei

Reputation: 988

I am not sure what you are looking for. But for this simple purpose, you can use:

x <- c(-2,3,-1,2,8)
x1 <- x[-length(x)]
z <- x[-1]
y <- z[z>0 & x1<0 & (z-x1)>2]
y

For operating on many 'x(t-i)', I don't know an elegant way, but you could try to wrap the uggly code in a function and then just call fts(x)

fts <- function(x){
  xmat <- sapply(1:10,function(i){
    x[-1:i]

  })
......
}

Also, for 'x(t)-x(t-1)', you can use diff(x); for x(t)-x(t-i) you can use diff(x,lag=i)

Upvotes: 1

Roland
Roland

Reputation: 132676

Not much different than the other answer, but a bit more compact:

x[x > 0 & 
    c(FALSE, head(x,-1) < 0) & 
    c(FALSE, diff(x) > 2)]

Upvotes: 1

Related Questions