library(gamlss.util)
# creating a linear + linear function
x <- seq(0,10, length.out=201)
knot <- 5
set.seed(12543)
mu <- ifelse(x<=knot,5+0.5*x,5+0.5*x+(x-knot))
y <- rNO(201, mu=mu, sigma=.5)
# plot the data
plot(y~x, xlim=c(-1,13), ylim=c(3,17))
# fit model using curfit
m1 <- fitFreeKnots(x, y, knots=4, degree=1)
# fitted values
lines(fitted(m1)~x, col="red", lwd="3")
# predict
pm1<-predict(m1, newdata=-1:12)
points(-1:12,pm1, col="red",pch = 21, bg="blue")
#------------------------------------------------
# now gamlss
#------------------------------------------------
# get the fk function
# fit model
g0 <- gamlss(y~fk(x, degree=1, start=c(4)))
# creating data frame
da <- data.frame(y,x)
g1 <- gamlss(y~fk(x, degree=1, start=c(4)), data=da)
nd<-data.frame(x=-1:12)
pg1<-predict(g1, newdata=nd)
lines(fitted(g1)~x, col="purple", lwd="3")
points(pg1~I(-1:12), col="darkgreen", pch = 21, bg="green" )
# note the predicting values outside the x-range
# it predicts the global linear fit
#-------------------------------------------------
#-------------------------------------------------
# now negative binomial data
eta1 <- ifelse(x<=knot,5+0.5*x,5+0.5*x+(x-knot))
set.seed(143)
y <- rNBI(201, mu=exp(eta1/7), sigma=.1)
da <- data.frame(y=y,x=x)
#rm(y,x)
plot(y~x, data=da)
# fitting the model in gamlss using profile deviance
n1 <- quote(gamlss(y ~ x+I((x>this)*(x-this)),family=NBI,data=da))
prof.term(n1, min=1, max=9, step=.1, criterion="GD")
# now fit the model using fk
g1 <- gamlss(y~fk(x, degree=1, start=c(4)), data=da, family=NBI)
# get the breakpoint
knots(g1$mu.coefSmo[[1]])
lines(fitted(g1)~x, data=da)
#------------------------------------------------
# the aids data
# using fk()
data(aids)
a1<-gamlss(y~fk(x, degree=1, start=25)+qrt, data=aids, family=NBI)
knots(a1$mu.coefSmo[[1]])
# using profile deviance
aids.1 <- quote(gamlss(y ~ x+I((x>this)*(x-this))+qrt,family=NBI,data=aids))
prof.term(aids.1, min=16, max=21, step=.1, criterion="GD")
# using non-linear estimation
library(gamlss.nl)
naids <- nl.obj(~p1*(x-p2)*I((x>p2)), start=c(0.2, 20), data=aids)
mod1 <- gamlss(y~nl(naids)+x+qrt, data=aids , family=NBI)
mod1$mu.coefSmo
GAIC(mod1,a1) # almost identical
# plotting the fit
with(aids, plot(x,y,pch=21,bg=c("red","green3","blue","yellow")[unclass(qrt)]))
lines(fitted(a1)~aids$x)
#-------------------------------------------------
Run the code above in your browser using DataLab