Skip to content

Instantly share code, notes, and snippets.

@vankesteren
Created April 1, 2022 07:11
Show Gist options
  • Save vankesteren/59223992e75417101901825473d72612 to your computer and use it in GitHub Desktop.
Save vankesteren/59223992e75417101901825473d72612 to your computer and use it in GitHub Desktop.
exponential decay with AR(1)
# exponential decay estimation with AR model
N <- 30
y <- numeric(N)
first_obs <- 2 # where do we start?
asymptote <- .5 # where do we go?
ar1_param <- .6 # how slow do we go there? (between -1 and 1)
sigma <- 0
y[1] <- first_obs
for (n in 2:N) {
y[n] <- asymptote + ar1_param*(y[n-1] - asymptote) + rnorm(1, sd = sigma)
}
plot(y, type = "l")
# now estimate an AR(1) model
first_dummy <- c(1, rep(0, N-1)) # dummy variable for first
y_lag <- c(0, y[-N]) # lagged y
res <- lm(y ~ 1 + first_dummy + y_lag) # estimate
# give the coefficients nice names
alpha <- unname(coef(res)[1])
phi <- unname(coef(res)[3])
first <- unname(coef(res)[2])
# now get the original parameters back
asymptote_estimated <- alpha / (1 - phi)
first_obs_estimated <- alpha + first
ar1_param_estimated <- phi
@vankesteren
Copy link
Author

# 4pl model
# https://www.myassays.com/four-parameter-logistic-regression.html

# 4pl model
upper_asymp <- 2
lower_asymp <- 0.5
inflect_pnt <- 50
slope_param <- 4
sigma <- 0
N <- 100
x <- 1:N
y <- upper_asymp + (lower_asymp - upper_asymp) / (1 + (x/inflect_pnt)^slope_param) + rnorm(N, sd = sigma)
plot(x, y)


infl <- 50
ylag <- c(y[2:infl], 0, y[infl:(N-1)])
infl_dummy <- c(rep(1, infl), rep(0, N-infl))
mid_dummy <- numeric(N); mid_dummy[infl] <- 1
fit <- lm(y ~ 0 + infl_dummy + I(1 - infl_dummy + mid_dummy) + mid_dummy + ylag)
lines(1:N, predict(fit, newdata = list(x = 1:N)))

# all that's needed now is to make sure there is no discontinuity in the gradient at the inflection point

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment