在布尔向量中找到 TRUE 的最长连续块 [英] Find the longest continuous chunk of TRUE in a boolean vector
问题描述
给定一个布尔向量,我怎样才能找到最长的连续块 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
?
例如,给定一个布尔向量:
For example, given a boolean vector:
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
and 还检查值本身是否为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 的最长连续块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!