计算R中连续的TRUE值的数量 [英] Count the number of consecutive TRUE values in R
问题描述
我想计算在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 TRUE
s. 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 TRUE
s 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屋!