Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Last active September 5, 2018 13:44
Show Gist options
  • Select an option

  • Save padpadpadpad/a83eefc5f859b2e2f2df3ca31122c1de to your computer and use it in GitHub Desktop.

Select an option

Save padpadpadpad/a83eefc5f859b2e2f2df3ca31122c1de to your computer and use it in GitHub Desktop.
Implement a simple decay model
# load packages
library(ggplot2)
library(broom)
# load in data
d <- read.csv('where/your/data/is.csv', stringsAsFactors = FALSE)
# try and fit an nls model using the exponential decay model
N(t) = N0 * e^-a*t
# N0 = number at t 0. here t is FiO2
# a is the decay parameter
# will shift the data by the minimum FiO2 to make it 0 and plug in the Altitude at that value
# work out minimum FiO2 for offset
FiO2_min <- min(d$FiO2)
start_alt <- d[d$FiO2 == FiO2_min,]$Altitude
# fit decay model
fit_decay <- nls(Altitude ~ 20000 * exp(-a * (FiO2 - 1.13)), d, start = c(a = 5), na.action = na.omit)
# quadratic fit, second order polynomial
fit_quadratic <- lm(Altitude ~ FiO2 + I(FiO2^2), d)
# compare model fits
AIC(fit_decay, fit_quadratic)
# get model predictions
preds_decay <- augment(fit_decay)
preds_quadratic <- augment(fit_quadratic)
# plot
ggplot() +
geom_point(aes(FiO2, Altitude), d) +
geom_line(aes(FiO2, .fitted), preds_decay, col = 'blue') +
geom_line(aes(FiO2, .fitted), preds_quadratic, col = 'red')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment