2016-09-19 57 views
0

我正在研究一个应用程序,用R和闪亮分析时间序列,并且我想绘制一个以帮助选择添加剂或乘法模型:1R - 找不到绘制最接近局部最大值的线的方法

我想绘制我的时间序列,也绘制两条线,分别与每个最大值和每个最小值分别最接近。

这里是一个图形的链接我想提醒:https://i.imgsafe.org/fdb95a34f9.png

对于这里的那一刻是我的代码,我打电话给我的功能plot_band

plot_band <- function(Xt, period){ 

    # Create an index 
    index <- 1:lenght(Xt) 

    # Create the vector period which value is the period the point belong to 
    periods <- index%/%period + 1 

    # Create a dataframe 
    df <- data.frame(xt= Xt,periods = as.factor(periods)) 

    # FInd the minimums and maximums 
    mins <- df[df$xt == ave(df$xt, df$period, FUN=min), ] 
    maxs <- df[df$xt == ave(df$xt, df$period, FUN=max), ] 

    # Regression with lm 
    mins_reg <- lm(mins$xt ~ mins$index) 
    maxs_reg <- lm(maxs$xt ~ maxs$index) 

    #And I don't know how to plot everything 
    my_graph <- ggplot(data=df, 

的另一个问题是,xt是一个ts格式,当它在参数中给出时,我不知道如何获得真实索引而不是索引N

回答

0

我终于找到了一个解决这个问题,它可能不是更好,但在这里它是:

plot_bande <- function(xt,period){ 

begin <- start(xt)[1] 
end <- end(xt)[1] 
freq <- frequency(xt) 

idx <- seq(begin,end,freq) 
periods <- idx %/% period + 1 - idx[1] %/% period 

df <- data.frame(data=xt,period=periods, idx=idx) 

df$period <- as.factor(df$period) 

min <- df[df$data == ave(df$data, df$period, FUN=min), ] 
max <- df[df$data == ave(df$data, df$period, FUN=max), ] 

reg_min <- lm(min$data ~ min$idx) 
reg_max <- lm(max$data ~ max$idx) 

a_min <- coef(reg_min)[1] 
b_min <- coef(reg_min)[2] 
a_max <- coef(reg_max)[1] 
b_max <- coef(reg_max)[2] 

plot(df$data) 
abline(a=a_min,b=b_min,col='blue') 
abline(a=a_max,b=b_max,col='red') 
legend('topleft', legend=c('Minimum values', 'Maximum values'),col=c('blue','red'), lty=1) 

}

你可以看到我用sunspot.year数据集获得的曲线图并点击这个12年期间link