我一直在try 将一些数据与某一x值范围内的平均y值的变化进行拟合.一段时间以来,我一直在努力让它发挥作用.
例如,给定一些受控随机数据和所需的拟合度:
library(tidyverse)
Data <- data.frame(Time = c(1:100, 101:500, 501:1000),
Value = c(runif(100, 0, 500),
runif(400, 500, 1000),
runif(500, 0, 100)),
Desired_fit = c(rep_len(250,100),
rep_len(750,400),
rep_len(50,500)))
plot(Data$Time, Data$Value)
lines(Data$Time, Data$Desired_fit, col = "red")
我try 平滑、获得运行平均值并对我的数据进行样条化,但这产生了一条曲线拟合,而不是上面期望的_Fit.本质上,我试图在数据集中的每个拐点上拟合一条水平线.
我try 过的最接近的方法是使用ZOO包中的RolMean():
library(zoo)
moving_average <- rollmean(Data$Value, 50, fill = NA)
plot(Data$Time, Data$Value)
lines(Data$time, moving_average, col = "red")
如有任何帮助或建议,将不胜感激!
谢谢!