这个问题在这里已经有了答案:
我如何计算序列中的运行? 2个答案我有一个二进制向量,我想统计我有多少个1的序列。 所以,如果我有像这样的矢量:
bin <- c(1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1)我会得到5 。 我还没有发现任何现有的功能可以做到这一点,任何人都可以得到关于如何写一个好的技巧? 当序列都有不同的长度时,我不知道如何构建“计数器”。
This question already has an answer here:
How can I count runs in a sequence? 2 answersI have a binary vector and I want to count how many sequences of 1's I've got. So that if I have a vector like:
bin <- c(1,1,0,1,1,1,1,0,0,0,1,0,1,1,0,0,1,1,1)I would get 5. I haven't found any existing functions that could do this, anyone got any good tips on how one could write one? I don't know how to build the "counter" when the sequences all have different lengths.
最满意答案
运行长度编码函数( rle )是为此而构建的。 在计算向量中等值运行的长度时,它会很有帮助,它会返回那些长度和值。 所以使用rle( bin ) 。
使用==比较$values输出与你想要的值( 1 ),并将结果sum (因为当值的运行是1时,你得到TRUE或1L ):
sum( rle(bin)$values == 1 ) [1] 5The run length encoding function (rle) is built for this. Helpfully whilst it computes the length of runs of equal values in a vector, it returns those lengths with the values. So use rle( bin ).
Compare the $values output to your desired value (1) with == and sum the result (because you get a TRUE or 1L when the run of values is of 1's):
sum( rle(bin)$values == 1 ) [1] 5更多推荐
发布评论