本文介绍了在布尔向量中找到最长的TRUE连续块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个布尔向量,如何找到最长的连续块TRUE
并将其余的TRUE
值更改为FALSE
?
Given a boolean vector, how can I find the longest continuous chunk of TRUE
and change the rest TRUE
values to FALSE
?
例如,给定布尔向量:
bool = c(TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE)
我如何获得像这样的向量:
How can I get a vector like:
c(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE)
推荐答案
这是一种在布尔向量中突出显示连续TRUE
的所有最长块的方法.这意味着,例如,如果有两个长度相同(最大)的TRUE
块,则在输出中都将报告为TRUE
.
Here's an approach that will highlight all longest chunks of consecutive TRUE
s in a boolean vector. That means, if there are, say, two TRUE
chunks of the same (max) length, both will be reported as TRUE
in the output.
我们可以使用:
with(rle(bool), rep(lengths == max(lengths[values]) & values, lengths))
这意味着:
-
with(rle(bool), ...)
:计算行程长度 -
lengths == max(lengths[values]) & values
:检查每个游程长度是否等于值TRUE
的最大游程长度,还检查值本身是否为TRUE
-
rep(...., lengths)
:按照自己的游程长度重复每个结果逻辑
with(rle(bool), ...)
: compute the run lengthslengths == max(lengths[values]) & values
: check if each run length is equal to the maximum run length where values isTRUE
and also check if values itself isTRUE
rep(...., lengths)
: repeat each of the resulting logicals as often as it's own run length
OP的测试用例:
bool <- c(TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE)
with(rle(bool), rep(lengths == max(lengths[values]) & values, lengths))
# [1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE
第二个测试用例:T和F的最大值相同:
Second test case: same maxima for T and F:
x <- c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE)
with(rle(x), rep(lengths == max(lengths[values]) & values, lengths))
# [1] TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
第三个测试用例:F比T更长的块:
Third test case: F longer chunk than T:
y <- c(TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE)
with(rle(y), rep(lengths == max(lengths[values]) & values, lengths))
# [1] TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
这篇关于在布尔向量中找到最长的TRUE连续块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!