计算R中连续的TRUE值的数量

编程入门 行业动态 更新时间:2024-10-10 11:28:34
本文介绍了计算R中连续的TRUE值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想计算在R中看到两个连续的TRUE值的次数.例如,

I would like to count how many times I see two consecutive TRUE values in R. For example,

x <- c(T,F,T,T,F,F,T,F,T,F) x [1] TRUE FALSE TRUE TRUE FALSE FALSE TRUE FALSE TRUE FALSE

因为在位置3有一个TRUE,在位置4有TRUE,所以它将计为1.如果有两个以上的连续TRUE,那么我只想对其计数一次,即此向量

It would count 1 since there is a TRUE at position 3 and TRUE at position 4. If there are more than 2 consecutive TRUE, then I just want to count it only once, ie this vector

x <- c(T,F,T,T,T,F,T,F,T,F) x [1] TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE TRUE FALSE

仍然会计数1.我从查看rle()开始,但是被卡住了.任何帮助将不胜感激.谢谢!

would still count 1. I started with looking at rle() but I got stuck. Any help would be greatly appreciated. Thanks!

推荐答案

这应该有效:

with(rle(x), sum(lengths[values] >= 2))

说明:

在使用布尔值时,您可以从中获利. rle(x)$lengths将返回向量中TRUE或FALSE连续出现的次数.例子

As you are using Booleans, you can take profit of it. rle(x)$lengths will return how many consecutive times TRUE or FALSE happen in the vector. Example

x <- c(T,F,T,T,T,F,T,F,T,F,T,T) rle(x)$lengths [1] 1 1 3 1 1 1 1 1 2

现在,您只希望此向量中与TRUE相对应的那些值. rle(x)$values返回具有出现顺序的向量.示例:

Now you only want those values in this vector that correspond to TRUEs. rle(x)$values returns a vector with the order of appearance. Example:

rle(x)$values [1] TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE

您可以使用它仅获取lengths向量中的TRUE:

You can use this to only get the TRUEs in the lengths vector:

rle(x)$lengths[rle(x)$values] [1] 1 3 1 1 2

最后一步应该很明显:计算多少个值等于或大于2.所有这些(一起提高了性能):

And the last step should be obvious: count how many of this values are grater or equal than 2. All together (with performance improvement):

with(rle(x), sum(lengths[values] >= 2)) [1] 2

更多推荐

计算R中连续的TRUE值的数量

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

发布评论

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

>www.elefans.com

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