Quantile Regression Notes and Illustration,    11/15/26
======================================================== E.Slud

## install packages quantreg, VGAM

 library(quantreg)
 library(VGAM)      ### for dataset  "melbmaxtemp", numeric time series of length 3650

 ord1 = order(melbmaxtemp[-3650])
 day1 = melbmaxtemp[-3650][ord1]
 nextday = melbmaxtemp[-1][ord1]

 plot(day1, nextday, cex=0.3, xlab="day.maxtemp", ylab="nextday.max",
     main=paste0("Day-Ahead Melbourne Max Temp, 1981-1990","\n",
              "via linear & quantile regression"))

 lsqfit = lm(nextday ~ day1)
 round(summary(lsqfit)$coef,3)
                   Estimate Std. Error t value Pr(>|t|)
(Intercept)           5.593      0.240  23.329        0
melbmaxtemp[-3650]    0.720      0.011  62.855        0

 
 lines(day1, lsqfit$coef[1]+lsqfit$coef[2]*day1, col="blue")

 ladfit = rq(nextday ~ day1)
 round(summary(ladfit)$coef,3)
            Value Std. Error t value Pr(>|t|)
(Intercept) 3.473      0.216  16.100        0
day1        0.818      0.015  55.204        0

lines(day1, ladfit$coef[1]+ladfit$coef[2]*day1, col="red")

 quant = c(.1, .25, .4, .6, .75, .9)
 for(i in 1:6) {
   rqfit = rq(nextday ~ day1, tau = quant[i])
   lines(day1, rqfit$coef[1]+rqfit$coef[2]*day1, col="orange") }

    #### saved as "QR-linear-MelbData.pdf"

  ### These lines are for the series of regression-quantiles

 ### THEY WOULD ALL BE PARALLEL IF THE ADDITIVE-ERROR REGRESSION MODEL HOLDS !!
 
 plot(day1, nextday, cex=0.3, xlab="day.maxtemp", ylab="nextday.max",
         main=paste0("Day-Ahead Melbourne Max Temp, 1981-1990","\n",
              "via log-log & quantile regression"))

 lsqft2 = lm(log(nextday) ~ log(day1))
 round(summary(lsqft2)$coef,3)
              Estimate Std. Error t value Pr(>|t|)
(Intercept)    0.693      0.032  21.938        0
log(day1)      0.765      0.011  71.947        0

 lines(day1, exp(lsqft2$coef[1]+lsqft2$coef[2]*log(day1)),  col="blue")
 ladft2 = rq(log(nextday) ~ log(day1))
 round(summary(ladft2)$coef,3)
            Value Std. Error t value Pr(>|t|)
(Intercept) 0.494      0.034  14.489        0
log(day1)   0.834      0.012  68.749        0            

lines(day1, exp(ladft2$coef[1]+ladft2$coef[2]*log(day1)), col="red")

 for(i in 1:6) {
   rqfit2 = rq(log(nextday) ~ log(day1), tau = quant[i])
   lines(day1, exp(rqfit2$coef[1]+rqfit2$coef[2]*log(day1)), col="orange") }

    #### saved as "QR-loglog-MelbData.pdf"

 ## This 2nd plot does a more interesting job of following the conditional quantiles
 ##    using loglog linear regressions (with additive indep errors on loglog scale
 ##------------------------------------------------------------------------------

### WITH SO MUCH DATA, WE CAN ESTIMATE CONDITIONAL QUANTILES, WITHOUT MODEL ASSUMPTION !!

 plot(day1, nextday, cex=0.3, xlab="day.maxtemp", ylab="nextday.max", xlim=c(13,33),
         main=paste0("Day-Ahead Melbourne Max Temp, 1981-1990","\n",
              "via smoothed nonparametric quantile regression"))

 rqfit3 = rqss(nextday ~ qss(day1, lambda=6))
 plot.rqss(rqfit3, add=T, col="red", titles="", rug=F, jit=F)
 for(i in 1:6) {
       rqfit3 = rqss(nextday ~ qss(day1, lambda=6), tau = quant[i])
       plot.rqss(rqfit3, add=T, col="orange", titles="", rug=F, jit=F) }

    #### saved as "QR-nonpar-MelbData.pdf"

   rqfit3 = rqss(nextday ~ day1, tau = quant[i])

 ### In Chapter 2 of the Koenker book, different smooth "conditional quantile regression" functions
###      are presented for these data. We can vary the smoothness as below, but 
###      he might have used a different method of computation.

  plot(day1, nextday, cex=0.3, xlab="day.maxtemp", ylab="nextday.max", xlim=c(13,33),
         main=paste0("Day-Ahead Melbourne Max Temp, 1981-1990","\n",
              "via smoothed nonparametric quantile regression"))

 rqfit3 = rqss(nextday ~ qss(day1, lambda=14))
 plot.rqss(rqfit3, add=T, col="red", titles="", rug=F, jit=F)
 for(i in 1:6) {
       rqfit3 = rqss(nextday ~ qss(day1, lambda=14), tau = quant[i])
       plot.rqss(rqfit3, add=T, col="orange", titles="", rug=F, jit=F) }


##===================== ADDITIONAL DATA ANALYSES,  11/23/26 ==========================
##
## First some examples taken from the "quantreg" vignette

                   ### Engel food expenditure vs income
  data(engel)
  plot(engel, main= "Engel Food Expenditure vs Income data (n=235)")      
                 ### looks like slightly downward-curving line with a few outliers at large x


  lm(log(engel$foodexp ~ log(engel$income)))$coef
       (Intercept) log(engel$income) 
        0.5451422         0.8558970 

   lin1 = lm(foodexp ~ income, data=engel)
Coefficients:
(Intercept)       income  
   147.4754       0.4852  

   lines(engel$income, lin1$fitted, col="blue")
   rq.5 = rq(foodexp ~income, data=engel)
              ### does a better job with slight curve at low income
  CI for income coef
   round(summary(rq.5)$coef[2,], 3) 
coefficients     lower bd     upper bd 
       0.560        0.487        0.602 

 lines(engel$income, rq.5$fitted, col="red")
 summary(rq.5, se="nid")

Call: rq(formula = foodexp ~ income, data = engel)

tau: [1] 0.5

Coefficients:
            Value    Std. Error t value  Pr(>|t|)
(Intercept) 81.48225 19.25066    4.23270  0.00003
income       0.56018  0.02828   19.81032  0.00000

 rq.mult = rq(foodexp ~ income, data=engel, tau= c(.1,.25,.75,.9))
 for(k in 1:4)  lines(engel$income, rq.mult$fitted[,k], col="orange")
          ### saved as "Engel.pdf"

### Why would we do the Quantile Regression fits here except to improve on or check the Linear Regression?

 par(mfrow=c(2,1))
 hist(lin1$resid, xlim=c(-1000,460), nclass=30, main="Linear fit Residuals")
 hist(rq.5$resid, xlim=c(-1000,460), nclass=30, main="Median regression residuals")
          ## saved as EngelResids.pdf

###  DO THE SAME SEQUENCE OF FITS AS LOG-LOG

 Engel.lglg = data.frame(log(data.matrix(engel)))
 plot(Engel.lglg, main= "Engel Food LogLog Expenditure vs Income data (n=235)")      
 lines(Engel.lglg$income, lm(foodexp~income, data=Engel.lglg)$fitted, col="blue")
 lines(Engel.lglg$income, rq(foodexp~income, data=Engel.lglg)$fitted, col="red")
 lines(rep(Engel.lglg$income,4), rq(foodexp~income, data=Engel.lglg, 
       tau=c(.1,.25,.75,.9))$fitted, col="orange")

### Now the quantile regressions look almost parallel !!?

> anova(rqlglg.5, rqlglg.25, rqlglg.75)
Quantile Regression Analysis of Deviance Table

Model: foodexp ~ income
Joint Test of Equality of Slopes: tau in {  0.5 0.25 0.75  }

  Df Resid Df F value Pr(>F)
1  2      703  2.0285 0.1323


 ###----------- 2nd example:  Brownlee (1965) from existing R datasets
 ###   variables    Air.Flow, Water.Temp, Acid.Conc., stack.loss
 ###   about         plant oxidation of ammonia to nitric acid

  data(stackloss)
  stack.rq50 = rq(stack.loss ~ ., data=stackloss)
  stack.rq25 = rq(stack.loss ~ ., data=stackloss, tau=0.25)
  stack.rqALL = rq(stack.loss ~ ., data=stackloss, tau= -1)

### Koenker [in the vignette and the rq() documentation] asks us to notice that many of the
### complete sequence of quantile regression coeffs are the SAME for these data !!

> round(stack.rqALL$sol, 3)
               [,1]    [,2]    [,3]    [,4]    [,5]    [,6]    [,7]    [,8]    [,9]   [,10]
tau           0.000   0.124   0.130   0.130   0.149   0.161   0.195   0.223   0.254   0.275
Qbar         13.454  13.994  15.310  15.310  15.310  15.310  15.310  15.310  15.310  16.161
Obj.Fun       0.000  10.606  11.047  11.062  11.948  12.473  14.047  15.375  16.810  17.792
(Intercept) -29.014 -36.078 -36.000 -36.000 -36.000 -36.000 -36.000 -36.000 -36.000 -37.897
Air.Flow      0.315   0.352   0.500   0.500   0.500   0.500   0.500   0.500   0.500   0.757
Water.Temp    1.224   1.750   1.000   1.000   1.000   1.000   1.000   1.000   1.000   0.794
Acid.Conc.   -0.028  -0.094   0.000   0.000   0.000   0.000   0.000   0.000   0.000  -0.098
              [,11]   [,12]   [,13]   [,14]   [,15]   [,16]   [,17]   [,18]   [,19]   [,20]
tau           0.331   0.375   0.392   0.409   0.490   0.565   0.592   0.604   0.620   0.651
Qbar         16.444  16.801  16.959  17.425  17.434  17.445  17.457  19.136  19.138  19.148
Obj.Fun      19.392  20.389  20.645  20.854  21.022  21.162  21.208  21.225  20.691  19.635
(Intercept) -38.527 -32.638 -33.246 -39.652 -39.690 -39.731 -39.681 -54.032 -54.065 -54.070
Air.Flow      0.843   0.825   0.849   0.830   0.832   0.834   0.836   0.873   0.873   0.871
Water.Temp    0.726   0.740   0.627   0.581   0.574   0.566   0.566   0.979   0.980   0.984
Acid.Conc.   -0.131  -0.186  -0.166  -0.062  -0.061  -0.060  -0.062  -0.003  -0.002  -0.002
              [,21]   [,22]   [,23]   [,24]   [,25]   [,26]   [,27]   [,28]   [,29]
tau           0.690   0.762   0.768   0.774   0.778   0.814   0.834   0.913   1.000
Qbar         19.156  19.193  19.715  19.989  20.121  20.161  20.206  21.701  21.701
Obj.Fun      18.319  15.837  15.615  15.363  15.168  13.171  12.084   7.626   0.000
(Intercept) -54.190 -54.091 -54.338 -56.683 -58.548 -59.375 -58.543 -58.462 -58.462
Air.Flow      0.871   0.864   0.777   0.786   0.808   0.806   0.793   0.525   0.525
Water.Temp    0.983   1.000   1.189   1.254   1.274   1.256   1.305   1.858   1.858
Acid.Conc.    0.000   0.000   0.024   0.032   0.034   0.050   0.038   0.107   0.107


### The tau values across the top are the breakpoints where the 4 (Int, Air.Flow,Water.Temp,Acid.Conc)
###   quantile regression coefficients change. The Table shows that for tau in te range [0.130, 0.275)
###   the QR coef’s are the SAME [up to machine 0] as 

  stack.rq25$coef
 (Intercept)     Air.Flow   Water.Temp   Acid.Conc. 
-3.60000e+01  5.00000e-01  1.00000e+00 -4.57967e-16 

###	 but of course, the outcomes  stackloss$stack.loss are not the same

 stackloss[3:10,4]
[1] 37 28 18 18 19 20 15 14

### This is an example of PIECEWISE CONSTANCY of the Quantile Regression across tau’s.

##================================================================================
## FINALLY, AN EXAMPLE WHERE THE QUANTILES [OF BIRTHWEIGHT OF INFANTS] ARE DIRECTLY OF INTEREST
##  [especially of interest longitudinally at later infant and child ages]

   library(MASS)
   data(birthwt)  ## 189 x 10 collected at Baystate Medical Center, Springfield, Mass during 1986

   birthwt = birthwt[,-1]  ## exclude “low” indicator of low birthweight, use only bwt birthweight in grams
   birthwt$race = factor(birthwt$race)               ### 3 levels 1=white, 2=black, 3=other 
   auxlin = step(lm(bwt ~ ., data=birthwt), scope = list(bwt ~ 1, bwt ~ .^2), direction="both")

   anova(auxlin)
Analysis of Variance Table                      ### no interactions important

Response: bwt
           Df   Sum Sq Mean Sq F value    Pr(>F)    
lwt         1  3448639 3448639  8.2654 0.0045226 **            ## mother’s weight
race        2  5076610 2538305  6.0836 0.0027701 ** 
smoke       1  6281818 6281818 15.0557 0.0001458 ***
ht          1  2871867 2871867  6.8830 0.0094402 **            ## history of hypertension
ui          1  6353218 6353218 15.2268 0.0001341 ***           ## “uterine irriatability”

   linwt = auxlin$fit
   plot(linwt, birthwt$bwt, xlab="linear fit", ylab="birth wt (grams)", main=
      "Birth Weights and Overlaid Quantile Regression Fits")
  bwt.rq = rq(bwt ~ lwt + race + smoke + ht + ui, data=birthwt, tau=c(.1,.25,.5,.75,.9))
  ord = order(linwt)
  for(k in 1:5) lines(linwt[ord], bwt.rq$fitted[ord,k], col="orange")

### Overlaid Quantile regression fits: vaguely parallel but not smooth at all !!!
       ###  saved as BwgtRQ.pdf
    
  anova(bwt.rq)
Quantile Regression Analysis of Deviance Table

Model: bwt ~ lwt + race + smoke + ht + ui
Joint Test of Equality of Slopes: tau in {  0.1 0.25 0.5 0.75 0.9  }

  Df Resid Df F value  Pr(>F)  
1 24      921  1.4675 0.06878
Warning message:
In summary.rq(x, se = se, R = R, covariance = TRUE) : 2 non-positive fis

### Let’s get a smoother version of the QR curves as functions of the linear fit
### (could also do this “nonparametrically” with additive univariate terms -- see below)

  plot(linwt, birthwt$bwt, xlab="linear fit", ylab="birth wt (grams)", main=
      paste0("Birth Weights and Overlaid Quantile Regression Fits", "\n",
            "(red lines are QR fits with respect to linear regr fit)") )
 
 bwgt.rqlin = rq(bwt ~ linwt, data=birthwt, tau=c(0.1,0.25,0.50,0.75,0.9))
 for(k in 1:5) lines(linwt[ord], bwt.rq$fitted[ord,k], col="orange")
 for(k in 1:5) lines(linwt, bwgt.rqlin$fit[,k], col="red")
          ###  saved as BwgtRQ2.pdf

  plot(linwt, birthwt$bwt, xlab="linear fit", ylab="birth wt (grams)", main=
      paste0("Birth Weights and Overlaid Quantile Regression Fits", "\n",
            "(blue lines are rqss fits with respect to regr variables)") )
  for(k in 1:5) {
      bwgt.rqss = rqss(bwt ~ qss(lwt, lambda=10) + race + smoke + ht + ui, 
           data=birthwt, tau=c(0.1,0.25,0.50,0.75,0.9)[k])
      lines(linwt[ord], fitted(bwgt.rqss)[ord], col="blue")  }
           #### too jagged and non-smooth to be useful



