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

如何检测并区分数值vector中的前3次独立涨幅并存储对应增量

实现方案

# 原始向量
vec <- c(5,5,11,11,7,16,16,16,12,8,20,24,20)

# 初始化参数
rise_count <- 0 # 独立上涨次数计数器
top3_rise <- c(NA, NA, NA) # 存储前3次涨幅
last_is_rise <- FALSE # 标记上一组相邻元素是否为上涨,避免连续上涨重复计数

# 遍历向量(从第2个元素开始和前一个对比)
for (i in 2:length(vec)) {
  current_diff <- vec[i] - vec[i-1]
  if (current_diff > 0 & !last_is_rise) {
    # 检测到新的独立上涨
    rise_count <- rise_count + 1
    top3_rise[rise_count] <- current_diff
    last_is_rise <- TRUE
    # 已经收集到前3次可以提前退出循环
    if (rise_count == 3) {
      break
    }
  } else if (current_diff <= 0) {
    # 出现持平或下跌,重置上涨标记
    last_is_rise <- FALSE
  }
}

# 输出结果
print(top3_rise) # 运行后得到 6 9 12

# 如果需要存为单独变量,直接赋值即可
rise1 <- top3_rise[1]
rise2 <- top3_rise[2]
rise3 <- top3_rise[3]

逻辑说明

  • 用last_is_rise标记位过滤连续上涨的情况,只有下跌/持平之后的第一次上涨才会被判定为新的独立上涨,完全匹配你对“独立上涨”的定义
  • 用计数器rise_count给不同次序的涨幅做索引,直接对应存入向量的对应位置,需要单独变量的话后续从向量里取即可
  • 收集到前3次涨幅后直接break跳出循环,不需要遍历完整个向量,效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:39:00