R/ADDline.R

Defines functions ADDline

Documented in ADDline

#' @title ‘ADDline’
#' @description create a list of line data based on ARIMA(X) predicted result or ts function result(i.e. time series data)
#'
#' @param ARIMAmodel ARIMA model created by function \code{auto.arima()}
#' @param XREG if using ARIMAX model, put in the regularized X matrix
#' @param TS data created by \code{ts()} function
#' @param linetype "TS" for time series data, "ARIMA" for ARIMA(X) predicted data
#' @param Name title for this line
#'
#' @author SOCR team <\url{http://socr.umich.edu/people/}>
#'
#' @details
#' This function \code{ADDline} is used to conduct a data transformation. It can take in original time-series data generated
#' by function \code{ts} or fitted ARIMA(X) model generated by function \code{auto.arima} then take out four elements from
#' those result to create a list which contains content that can be put in function \code{add_lines} or \code{add_trace}.
#' So that we could add new lines in our plotly plot more easily.
#'
#' @return a list contains 4 elements:
#' \item{X}{data put in parameter "x" of plot_ly function}
#' \item{TEXT}{rename the lable of variable X}
#' \item{Y}{data put in parameter "y" of plot_ly function}
#' \item{NAME}{title of the new line}
#' @export
#'
#' @import forecast zoo plotly prettydoc
#' @importFrom stats time
#'
#' @examples
#' require(forecast)
#' require(zoo)
#' require(plotly)
#'
#' #Firstly create a base plotly plot
#' Tempplot<-TSplot(48,modArima_train,as.matrix(X_test),title_size = 8,
#' ts_original = "Original time series",ts_forecast = "Predicted time series")
#'
#' # Generate a new line with ADDline function
#' newline<-ADDline(TS = MCSI_Data_monthAvg_ts_Y_test,linetype = "TS",Name = "Original Result")
#'
#' ## Put the new line into our plot
#' Tempplot%>%
#'   add_lines(x=newline$X,text=newline$TEXT,y=newline$Y,name=newline$NAME,line=list(color="grey"))
#'
ADDline <- function(ARIMAmodel=NULL,XREG=NULL,TS=NULL,linetype="TS",Name=NULL) {
  if(linetype=="ARIMA"){
    tsmodel<-forecast(ARIMAmodel, xreg = XREG)
    newline<-list(X=as.yearmon(time(tsmodel$x)),TEXT=as.character(as.yearmon(time(tsmodel$x))),Y=tsmodel$mean,NAME=Name)
  }
  else if(linetype=="TS"){
    newline<-list(X=as.yearmon(time(TS)),TEXT=as.character(as.yearmon(time(TS))),Y=as.numeric(TS),NAME=Name)
  }
  return(newline)
}

Try the TSplotly package in your browser

Any scripts or data that you put into this service are public.

TSplotly documentation built on Aug. 2, 2019, 5:04 p.m.