计算R中连续的TRUE值的数量 [英] Count the number of consecutive TRUE values in R

查看:870
本文介绍了计算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将返回向量中TRUEFALSE连续出现的次数.例子

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值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆