; Tutorial Quantile regression
;
; quantlet for running five QR regression and drawing regression curves
;
proc() = olsqr(x, y, t1, step, num, graph)
; initialization
id = 1
tau = t1
n = rows(x)
p = cols(x)
colors = #(1,2,4,2,1)
;
xgr = x[,graph]
yhat = matrix(n,num+2)
yhat[,1] = y
;
; compute OLS
beta = gls(x,y)
yhat[,2] = x * beta
;
; compute QR
while (id <= num)
z = rqfit(x,y,tau)
beta = z.coefs
yhat[,id+2] = x * beta
; increase tau and counter
tau = tau + step
id = id + 1
endo
;
; prepare drawing data
d1 = xgr~yhat[,1]
setmaskp(d1, 0, 8, 4)
d2 = xgr~yhat[,2]
setmaskp(d2, 0, 0, 0)
setmaskl(d2, (1:n)', 0, 1, 2)
d3 = xgr~yhat[,3]
setmaskp(d3, 1, 0, 0)
setmaskl(d3, (1:n)', 1, 1, 1)
d4 = xgr~yhat[,4]
setmaskp(d4, 2, 0, 0)
setmaskl(d4, (1:n)', 2, 1, 1)
d5 = xgr~yhat[,5]
setmaskp(d5, 4, 0, 0)
setmaskl(d5, (1:n)', 4, 1, 1)
d6 = xgr~yhat[,6]
setmaskp(d6, 2, 0, 0)
setmaskl(d6, (1:n)', 2, 1, 1)
d7 = xgr~yhat[,7]
setmaskp(d7, 1, 0, 0)
setmaskl(d7, (1:n)', 1, 1, 1)
;
; draw graph
d = createdisplay(1,1)
show(d, 1, 1, d1, d2, d3, d4, d5, d6, d7)
setgopt(d, 1, 1,"title","VitaminC data - OLS and QR")
endp
;
; main part
;
library("metrics")
;
z = read("vitaminc")
sel = sort(#(1:rows(z)) .* (z[,4] == 0))
sel = sel[sum(sel==0)+1:rows(sel)]
z = z[sel,]
;
x = matrix(rows(z))~z[,2]
y = z[,3]/100
;
olsqr(x, y, 0.1, 0.2, 5, 2)