计数载体中序列的数量[重复](Counting number of sequences in a vector [duplicate])

编程入门 行业动态 更新时间:2024-10-27 16:33:42
计数载体中序列的数量[重复](Counting number of sequences in a vector [duplicate])

这个问题在这里已经有了答案:

我如何计算序列中的运行? 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 answers

I 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] 5

The 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

更多推荐

本文发布于:2023-07-27 15:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292445.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   载体   数量   Counting   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!