查找值变化/信号开关的行索引

时间:2013-07-16 23:08:31

标签: r indexing row subset

我有一个二进制信号突发的数据表随着时间的推移。那些信号突发是随机长度的。所以我需要找到从0到1(起点)的行索引,以及发生1到0(终点)变化的行索引。所以最终我可以找到每个信号突发的开始和结束时间。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

假设您的数据如下:

R> x
      V1 V2 V3 V4 V5
 [1,]  0  0  0  0  1
 [2,]  0  1  0  0  1
 [3,]  1  1  0  0  1
 [4,]  1  1  0  0  1
 [5,]  1  1  1  0  1
 [6,]  1  1  1  0  1
 [7,]  1  1  1  0  0
 [8,]  1  1  1  0  0
 [9,]  1  1  1  0  0
[10,]  1  1  1  1  0
[11,]  1  0  1  1  0
[12,]  1  0  1  1  0
[13,]  1  0  1  1  0
[14,]  1  0  1  1  0
[15,]  1  0  1  1  0
[16,]  1  0  1  1  0
[17,]  1  0  1  1  0
[18,]  0  0  1  1  0
[19,]  0  0  1  0  0
[20,]  0  0  1  0  0

我会这样做:

apply(x, 2,
      function (k) {
        w <- which(k == 1, arr.ind=TRUE)
        c(head(w, 1), tail(w, 1))
      })

    V1 V2 V3 V4 V5
[1,]  3  2  5 10  1
[2,] 17 10 20 18  6

答案 1 :(得分:1)

您可以使用评论中提到的diffrle。但你应该提供:

  1. 信号示例

     set.seed(1)
     rr <- rbinom(30,1,0.5)
    
  2. 你尝试过什么?以diff为例,我执行以下操作

    ind <- c(0,diff(rr))
    
  3. 预期产量?

    start <- min(which(ind==1)) ##  change from 0 to 1 (the start point)
    end <- max(which(ind==-1))  ##  change of 1 to 0 (the end point)