R/GMM_Statistics.R

Defines functions GMM_Statistics

Documented in GMM_Statistics

#'@title A function that run linear regression model estimated by GMM over the model matrix
#'@description A function that calculate the R squared of a linear regression model estimated by GMM for RV prediction.
#'
#'@param MM a matrix of the model matrix.
#'
#'@return a vector for GMM R squares with 14 different designs.
#'@import gmm
#'
#'@export
GMM_Statistics <- function(MM){

  return_matrix = matrix(NA,nrow = 3, ncol = 4)
  rownames(return_matrix) = c("coef_est","pvalue","adj_Rsquared")
  colnames(return_matrix) = c("V_nof","TN_nof","V_filter","TN_filter")

  MM = MM[,colnames(MM) != "X"]
  indx_basic = grepl("Monday|Y",colnames(MM))
  MM = na.omit(MM)
  MM = as.data.frame(scale(MM))

  #define a helper function
  gmmlm_R2 <- function(Model_M){
    res <- gmm(Y ~ ., x = Model_M[,-1*which(colnames(Model_M)=="Y")], data = Model_M)
    statistics <- summary(res)
    R2 <-  summary( lm(Model_M$Y~fitted.gmm(res) - 1) )$r.squared
    n = nrow(Model_M)
    p = ncol(Model_M) - 1
    adj_R2 = 1-(1-R2)*((n-1)/(n-p-1))
    return(c(statistics$coefficients[3,1],statistics$coefficients[3,4],adj_R2))
  }

  return_matrix[,1] =  gmmlm_R2(MM[,indx_basic|colnames(MM) == "V_raw"])
  return_matrix[,2] =  gmmlm_R2(MM[,indx_basic|colnames(MM) == "TN_raw"])
  return_matrix[,3] =  gmmlm_R2(MM[,indx_basic|colnames(MM) == "V_weekly_stl"])
  return_matrix[,4] =  gmmlm_R2(MM[,indx_basic|colnames(MM) == "TN_weekly_stl"])

  return(return_matrix)
}
ZhenWei10/Sherry-Chapter1 documentation built on Oct. 31, 2019, 1:48 a.m.