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

如何过滤趋势?基于给定R代码生成带阈值的新趋势向量

趋势过滤与自定义阈值实现方案

针对你提供的带噪声分段趋势数据,下面给出几种可自定义阈值的趋势过滤方法,生成新的趋势向量:

1. 偏差阈值过滤

通过设定观测值与原始趋势mu的偏差阈值,控制是否保留原始趋势或噪声观测值:

set.seed(1)
n=1000
mu = c(rep(1,100),rep(3,100),rep(5,100),rep(2,100),rep(1,600))
y = mu + rnorm(n)

# 设定允许的最大偏差阈值
dev_threshold <- 0.8
# 当偏差超过阈值时用原始趋势值替代,否则保留观测值
filtered_trend_dev <- ifelse(abs(y - mu) > dev_threshold, mu, y)

2. 绝对阈值过滤

设定观测值的上下限阈值,将超出范围的点截断到阈值:

# 自定义上下限阈值
upper_thresh <- 6
lower_thresh <- 0
filtered_trend_abs <- ifelse(y > upper_thresh, upper_thresh, ifelse(y < lower_thresh, lower_thresh, y))

3. 滑动窗口平滑(窗口大小作为平滑阈值)

用滑动窗口的均值/中位数过滤噪声,窗口大小决定平滑程度(窗口越大,过滤效果越强):

library(zoo)
# 自定义窗口大小(平滑阈值)
window_size <- 11
# 滑动中位数过滤(抗异常值能力更强)
filtered_trend_rollmed <- rollmedian(y, k = window_size, fill = "extend")
# 滑动均值过滤
filtered_trend_rollmean <- rollmean(y, k = window_size, fill = "extend")

4. LOESS局部回归(平滑度参数作为阈值)

通过局部回归拟合提取趋势,span参数控制平滑程度(值越大,趋势越平滑):

# 自定义平滑度阈值span(0~1之间)
loess_span <- 0.1
loess_fit <- loess(y ~ seq_along(y), span = loess_span)
filtered_trend_loess <- predict(loess_fit)

5. 分段趋势识别阈值

设定各趋势段的数值阈值,将观测值归类到对应的趋势段:

library(dplyr)
# 自定义每个趋势值的允许偏差阈值
seg_threshold <- 0.5
filtered_trend_seg <- case_when(
  abs(y - 1) <= seg_threshold ~ 1,
  abs(y - 2) <= seg_threshold ~ 2,
  abs(y - 3) <= seg_threshold ~ 3,
  abs(y - 5) <= seg_threshold ~ 5,
  TRUE ~ y  # 未匹配的点保留原始值
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:20:34