【问题标题】:R: Count of consecutive numbers over arrayR:数组中连续数字的计数
【发布时间】:2015-01-29 15:22:51
【问题描述】:

我试图在 R 中的数组的第三维上找到连续“1”的最大数量。该数组由“0”和“1”组成。这是一个例子:

my_array <- array(c(1,1,1,0,1,1,0,0,1,0,0,1,0,0,1,1,1,0,1,1), dim=c(2,2,5))

我尝试过:

apply(my_array,c(1,2),rle)

但是结果不是很直接,理想情况下,结果矩阵应该是这样的:

     [,1] [,2]
[1,]    3    2
[2,]    2    3

R中还有比rle()更充分的函数吗?

【问题讨论】:

    标签: arrays r apply


    【解决方案1】:

    使用我的“SOfun”包 (only on GitHub) 中的 TrueSeq,正如我对 surprisingly similar question 的回答中提到的那样,您可以这样做:

    library(SOfun)
    apply(my_array, c(1, 2), function(x) max(tabulate(TrueSeq(as.logical(x)))))
    #      [,1] [,2]
    # [1,]    3    2
    # [2,]    2    3
    

    【讨论】:

      【解决方案2】:

      试试这个:

      apply(my_array,c(1,2),function(x){
                               max(rle(x)$length[rle(x)$values=="1"])
                             })
      
      #     [,1] [,2]
      #[1,]    3    2
      #[2,]    2    3
      

      【讨论】:

      • 感谢您的快速响应,它运行良好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2020-09-26
      相关资源
      最近更新 更多