if (FALSE) {
set.seed(18121)
nn <- 300
x2 <- sort(runif(nn, 0, 3)) # Predictor/covariate.
bb <- exp(1.1 + 0.2 * x2) # Scale parameter as function of x2.
aa <- exp(1.0 - 0.35 * x2) # Shape parameter as function of x2.
mymu <- bb * gamma(1 + 1/aa) # The Weibull mean.
## Use weibullMlink to generate appropriate scale parameter.
newbb <- weibullMlink(theta = log(mymu), shape = aa, inverse = TRUE, deriv = 0)
## A single random response
wdata <- data.frame(y1 = rweibull(nn, shape = aa, scale = newbb), x2 = x2)
# Plotting the data / Histogram
plot(y1 ~ x2, xlim = c(0, 3.1), ylim = c(-1, 35),
pch = 20, data = wdata, col = "black",
main = "Weibull Quantile regression~ x2")
abline(h = 0, v = 0, col = "grey", lty = "dashed")
with(wdata, hist(y1, col = "red", breaks = 15))
## Weibull regression - percentile = c(25, 50, 75)
## Note the use of Q.reg.
fit1 <- vglm(Q.reg(y1, length.arg = 3) ~ x2,
weibullRff(link1 = "weibullQlink", zero = NULL,
percentile = c(25, 50, 75)),
trace = TRUE, data = wdata)
head(fitted(fit1))
summary(fit1)
my.coef3Q <- coef(fit1, mat = TRUE)
### Proportion of data below the estimated 25% Quantile line.
100 * (1 - (sum(wdat$y1 >= fitted(fit2)[, 1]) / nn)) # Around 25%
### Proportion of data below the estimated 50% Quantile line.
100 * (1 - (sum(wdat$y1 >= fitted(fit2)[, 2]) / nn)) # Around 50%
### Proportion of data below the estimated 75% Quantile line.
100 * (1 - ( sum(wdat$y1 >= fitted(fit2)[, 3]) / nn )) # Around 75%
## The quantile plots ##
my.coef3Q <- coef(fit2, matrix = TRUE)
with(wdat, lines(x2, exp(my.coef3Q[1, 1] + my.coef3Q[2, 1] * x2),
col = "red", lty = "dotted", lwd = 4))
with(wdat, lines(x2, exp(my.coef3Q[1, 3] + my.coef3Q[2, 3] * x2),
col = "orange", lty = "dotted", lwd = 4))
with(wdat, lines(x2, exp(my.coef3Q[1, 5] + my.coef3Q[2, 5] * x2),
col = "blue", lty = "dotted", lwd = 4))
## Adding the 'mean' or expected Weibull regression line.
fit2 <- vglm(y1 ~ x2,
weibullRff(link1 = "weibullMlink", zero = NULL),
trace = TRUE, data= wdat)
my.coef3Q <- coef(fit2, mat = TRUE)
with(wdat, lines(x2, exp(my.coef3Q[1, 1] + my.coef3Q[2, 1] * x2),
col = "yellow", lty = "dashed", lwd = 3))
legend("topleft", c("25h Perc", "50th Perc", "Mean", "75th Perc"),
col = c("red", "orange", "cyan", "blue"),
lty = c("dashed", "dashed", "dashed", "dashed"), lwd = rep(4, 4))
}
Run the code above in your browser using DataLab