R/swr.r

Defines functions qwdap.swr

Documented in qwdap.swr

#' @title Model by Stepwise Regression
#' @description Stepwise regression. This is a linear regression method used to
#' establish the linear relationship between the original time series and the modes
#' generated by quantum walks.
#' @usage qwdap.swr(in_data, data_range, plotting)
#' @param in_data a 'QWMS' object, which includes the target series and the
#' selected modes which can be obtained from modes selection.
#' @param data_range the range of the train samples.
#' @param plotting whether to plot.
#'
#' @return a 'QWMODEL' object which includes the information of regression analysis.
#' @importFrom stats lm as.formula step
#' @importFrom graphics lines legend
#' @export qwdap.swr
#'
#' @examples
#' data("traffic.n1")
#' res.swr <- qwdap.swr(traffic.n1,c(1,500))
#' 
qwdap.swr <- function(in_data, data_range, plotting = FALSE){
  if(!inherits(in_data, 'QWMS')){
    stop("The 'in_data' is not a 'QWMS' object.")
  }
  if(!is.vector(data_range)||!is.numeric(data_range)||length(data_range)<2){
    stop("The parameter 'data_range' is error.")
  }
  # pre combine
  co_data = cbind(in_data$real, in_data$ctqw)
  co_data <- subset(co_data, select = c(colnames(in_data$real), in_data$variate))
  # data_y=in_data$real[data_range[1]:data_range[2],]
  # data_x=in_data$ctqw[data_range[1]:data_range[2],]
  #colnames(data_y)<-c("y")
  # lm_1 = colnames(data_y)
  # lm_2 = colnames(data_x)
  my_lm = paste(colnames(co_data)[1],"~",paste(colnames(co_data)[-1],collapse = " + "))
  my_lm = lm(as.formula(my_lm),data = as.data.frame(co_data[data_range[1]:data_range[2],]))
  res<-step(my_lm,direction = "forward")
  detail <- summary(res)
  if(plotting){
    tmp_data = cbind(in_data$real[data_range[1]:data_range[2],],res$fitted.values)
    colnames(tmp_data)=c("Actual series","Fitted series")
    plot(x=c(1:nrow(tmp_data)),y=tmp_data[,1],type = "l",xlab="index",ylab="value",
         ylim=c(min(tmp_data)-2,max(tmp_data)+2),lwd=1)
    lines(x=c(1:nrow(tmp_data)),y=tmp_data[,2],type = "l",col=2,lwd=1)
    legend("topleft", colnames(tmp_data), col = c(1,2),
           lwd = c(1), bg = "grey95", box.col = NA,
           cex = 0.8, inset = c(0.02, 0.03), ncol = 1)
  }
  # tmp_data = cbind(data_y,res$fitted.values)
  # colnames(tmp_data) = c("pre_value","fitted_value")
  # return(list("value"=tmp_data,"Multiple R-squared"=detail$r.squared,"Adjusted R-squared"=detail$adj.r.squared,
  #             "Parameters"=res$coefficients))
  res<-list(real = in_data$real, ctqw = co_data[,-1], index = in_data$index,
            method = "Stepwise Regression",model=res)
  res<-structure(res,class="QWMODEL")
  return(res)
}

Try the QWDAP package in your browser

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

QWDAP documentation built on May 29, 2024, 2:01 a.m.