我想计算在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值的数量
发布评论