You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

序列计数需求:统计连续低于阈值的元素个数并重置计数

Solution for Counting Consecutive Elements Below a Threshold in R

Perfect question—this is exactly the kind of problem R's built-in rle() function was made for! Let's walk through a straightforward solution step by step:

Step 1: Set up your data and threshold

First, let's define the example sequence and threshold you provided:

X <- c(1,2,11,14,5,6,7,12)
threshold <- 10

Step 2: Mark elements below the threshold

Create a logical vector where each entry is TRUE if the element is less than the threshold, and FALSE otherwise:

below_threshold <- X < threshold
# Result: [TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE]

Step 3: Count consecutive runs with rle()

The rle() (run-length encoding) function breaks sequences into consecutive "runs" of identical values, returning a list with two parts: lengths (how long each run is) and values (what the value of the run is). We'll filter this to keep only the lengths of runs where the value is TRUE (i.e., consecutive elements below the threshold):

run_stats <- rle(below_threshold)
output <- run_stats$lengths[run_stats$values]

Step 4: Verify the result

If you run this code, you'll get exactly the output you wanted:

> output
[1] 2 3

How this works

  • rle(below_threshold) splits our logical vector into four runs: 2 TRUEs, 2 FALSEs, 3 TRUEs, 1 FALSE.
  • By indexing run_stats$lengths with run_stats$values, we only keep the lengths of the runs where the value was TRUE—the consecutive sequences below the threshold.

For a tidyverse alternative (using dplyr), here's another way to get the same result:

library(dplyr)

tibble(value = X) %>%
  mutate(below = value < threshold,
         # Create groups separated by elements above the threshold
         group = cumsum(!below)) %>%
  filter(below) %>%
  count(group) %>%
  pull(n)

This will also return [2, 3], by grouping consecutive below-threshold elements using a cumulative sum of "above threshold" markers.

内容的提问来源于stack exchange,提问作者Sunichie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:10:19