在布尔向量中找到 TRUE 的最长连续块 [英] Find the longest continuous chunk of TRUE in a boolean vector

查看:17
本文介绍了在布尔向量中找到 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?

例如,给定一个布尔向量:

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 TRUEs 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 lengths
  • lengths == max(lengths[values]) & values: check if each run length is equal to the maximum run length where values is TRUE and also check if values itself is TRUE
  • 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屋!

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