【问题标题】:Finding the start and stop indices in sequence in R在R中按顺序查找开始和停止索引
【发布时间】:2015-05-24 21:52:03
【问题描述】:

假设我有序列:

x = c( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0)

在 R 中是否有一种优雅的方式来返回每个 1 序列的开始和停止索引?

答案应该是一个 2 列数组,其中 nRows = 1 的序列数:

startIndx = [ 1, 5, 7 ]
stopIndex = [ 2, 5, 9 ]

谢谢。

BSL

【问题讨论】:

    标签: r pattern-matching sequence indices


    【解决方案1】:

    这个呢? [根据alexis_laz的建议编辑版本]

    library(cgwtools)
    res <- seqle(which(as.logical(x)))
    rbind(res$values, res$values + res$lengths - 1)
         [,1] [,2] [,3]
    [1,]    1    5    7
    [2,]    2    5    9
    

    【讨论】:

    • 除非我遗漏了什么,否则您可以将最后一行替换为 rbind(res$values, res$values + res$lengths - 1)
    • 感谢您的建议,现在更容易阅读/理解 :)
    【解决方案2】:

    假设您的向量由 0 和 1 值组成:

    which(diff(c(0L, x)) == 1L)
    #[1] 1 5 7
    which(diff(c(x, 0L)) == -1L)
    #[1] 2 5 9
    

    否则你首先需要x &lt;- x == 1L 之类的东西。

    【讨论】:

      【解决方案3】:

      优雅的方式是

      y <- which(x==1)
      startIndx <- y[!(y-1) %in% y]
      stopIndex <- y[!(y+1) %in% y]
      rbind(startIndx, stopIndex)
      #          [,1] [,2] [,3]
      #startIndx    1    5    7
      #stopIndex    2    5    9
      

      【讨论】:

      • 正在看哪个 ;) 太棒了!
      【解决方案4】:

      试试这个:

      y = rle(x)
      
      stopIndex  = with(y, cumsum(lengths)[values==1])
      startIndex = stopIndex - with(y, lengths[values==1]) + 1
      
      #> stopIndex
      #[1] 2 5 9
      #> startIndex
      #[1] 1 5 7
      

      【讨论】:

        【解决方案5】:

        这个怎么样:

        startIndx<-rev(length(x)-cumsum(rle(rev(x))$lengths)[rle(rev(x))$values==1]+1)
        stopIndex<-cumsum(rle(x)$lengths)[rle(x)$values==1]
        

        【讨论】:

          猜你喜欢
          • 2020-08-24
          • 1970-01-01
          • 2016-10-27
          • 1970-01-01
          • 2020-06-20
          • 1970-01-01
          • 2021-05-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多