Skip to content

Instantly share code, notes, and snippets.

@MJacobs1985
Created October 3, 2021 19:45
Show Gist options
  • Select an option

  • Save MJacobs1985/f1b8af9cace496966429ba2d740d90ef to your computer and use it in GitHub Desktop.

Select an option

Save MJacobs1985/f1b8af9cace496966429ba2d740d90ef to your computer and use it in GitHub Desktop.
NLMIXED in R
#### Plotting NLMIXED Model #####
try.nlm2<-nlme(y~U+D*exp(-(Kd*x)),
data=Grass_compl,
fixed=U+D+Kd~1,
random=U+D+Kd~1|Trial/Cow,
start=c(U=20,D=50.88,Kd=0.02698),
method="ML",
control=nlmeControl(maxIter=1000, msMaxIter = 100))
pdata<-expand.grid(x=as.numeric(0:350),
Trial=unique(Grass_compl$Trial),
Cow=unique(Grass_compl$Cow))
pdata2<-as.data.frame(predict(try.nlm2, newdata=pdata, level=0:2)) # predict for all three levels --> predict.fixed, predict.trial, predict.Cow
head(predict(try.nlm2, newdata=pdata, level=0:2))
pdata<-cbind(pdata,pdata2[,2:5])
rm(pdata2)
pdata<-pdata[,c(1:2,4:7)]
myx<-scale_x_continuous(breaks=c(0,8,16,32,56,96,336))
myy<-scale_y_continuous(breaks = seq(0, 80, by = 10))
ggplot(Grass_compl, aes(x=x,y=y))+
myx+
myy+
labs(title = "DM residue over time in 8 Trials / 39 Cows", y="DM residue", x="Time (hours)")+
geom_point(colour="grey80")+
theme_bw()+
geom_line(data=pdata, aes(y=predict.Cow, group=Cow, colour="Cow"),lwd=1, alpha=0.5)+
geom_line(data=pdata, aes(y=predict.Trial, group=Trial, colour="Trial"),lwd=2, alpha=0.7)+
geom_line(data=pdata, aes(y=predict.fixed, colour="Population"),lwd=2.5, alpha=1)+
scale_colour_manual(name="Line Color",
values=c(Cow="blue", Trial="green", Population="red"))
myx<-scale_x_continuous(breaks=c(0,8,16,32,56,96,336))
myy<-scale_y_continuous(breaks = seq(0, 80, by = 10))
ggplot(Grass_compl, aes(x=x,y=y, colour=Trial))+
myx+
myy+
labs(title = "DM residue over time in 8 Trials / 39 Cows", y="DM residue", x="Time (hours)")+
geom_point(colour="grey80")+
theme_bw()+
geom_line(data=pdata, aes(y=predict.Cow, group=Cow),lwd=0.7, alpha=0.3)+
geom_line(data=pdata, aes(y=predict.Trial, group=Trial),lwd=1.5, alpha=1)+
geom_line(data=pdata, aes(y=predict.fixed), colour="black",lwd=2, alpha=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment