简体   繁体   English

基于前一行的R中的逻辑向量

[英]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 更具体地说,使用时间序列表示法(我编写了第二行),我希望得到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. 我真的不需要y的解决方案,因为我总是可以循环它。 But would be very interested to know if there is a shift operator or something similar for logical vector indexing 但是非常有兴趣知道是否存在移位运算符或类似的逻辑向量索引

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(ti)', 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) 对于许多'x(ti)'的操作,我不知道一种优雅的方式,但你可以尝试将uggly代码包装在一个函数中然后只调用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) ; 另外,对于'x(t)-x(t-1)' ,你可以使用diff(x) ; for x(t)-x(ti) you can use diff(x,lag=i) 对于x(t)-x(ti)你可以使用diff(x,lag=i)

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

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 它非常优雅地处理lag(x,-i)而无需调整矢量大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM