2016-09-19 58 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