我想使用 FFT 将波拟合到时间序列。
目标是绘制具有不同谐波的图,并用它来预测 n 个数据点。
我正在使用的代码基于此answer https://stackoverflow.com/questions/41435777/perform-fourier-analysis-to-a-time-series-in-r from @灾难性故障 https://stackoverflow.com/users/2874779/catastrophic-failure
nff = function(y = NULL, n = NULL, up = 10L, plot = TRUE, add = FALSE, main = NULL, ...){
#The direct transformation
#The first frequency is DC, the rest are duplicated
dff = fft(y)
#The time
t = seq(from = 1, to = length(y))
#Upsampled time
nt = seq(from = 1, to = length(y)+1-1/up, by = 1/up)
#New spectrum
ndff = array(data = 0, dim = c(length(nt), 1L))
ndff[1] = dff[1] #Always, it's the DC component
if(n != 0){
ndff[2:(n+1)] = dff[2:(n+1)] #The positive frequencies always come first
#The negative ones are trickier
ndff[length(ndff):(length(ndff) - n + 1)] = dff[length(y):(length(y) - n + 1)]
}
#The inverses
indff = fft(ndff/as.integer(length(y)), inverse = TRUE)
idff = fft(dff/as.integer(length(y)), inverse = TRUE)
if(plot){
if(!add){
plot(x = t, y = y, xlab = "Time", ylab = "Data",
main = ifelse(is.null(main), paste(n, "harmonics"), main), type="l", col="green")
lines(y = Mod(idff), x = t, col = "red")
}
lines(y = Mod(indff), x = nt, ...)
}
ret = data.frame(time = nt, y = Mod(indff))
return(ret)
}
对我来说,问题是,因为我的数据集中也有负值,所以我无法弄清楚为什么包含正值。
这是原著的剧情data https://drive.google.com/drive/folders/1P_oRxJW82OrdDOB8ND5Xd6I-COgGZveM?usp=sharing
与 fft 后的图相比
我如何调整代码,使谐波也涵盖缺失的负值,以及如何使用它来计算(预测)接下来的 n 个时间点?