Skip to content

Instantly share code, notes, and snippets.

@cbrown5
Created March 22, 2018 05:53
Show Gist options
  • Save cbrown5/32f5a41beeb99e4a2de01c602190516b to your computer and use it in GitHub Desktop.
Save cbrown5/32f5a41beeb99e4a2de01c602190516b to your computer and use it in GitHub Desktop.
A simple demonstration of retransformation bias in log-linear models
#
# Simulate data
#
a <- 2
x <- seq(0, 1, length.out = 100)
n <- length(x)
sigma <- 0.5
set.seed(42)
lny <- rnorm(n, mean = a*x, sd = sigma)
y <- exp(lny)
#
# Expectations
#
yexpect <- a*x #linear predictor on log scale
expyexpect <- exp(yexpect) #incorrect expectation, just the exponent of the linear predictor
m <- exp(yexpect + (sigma^2)/2) #correct mean, accounts for errors
sd <- sqrt(exp(2 * yexpect + sigma^2)* (exp(sigma^2)-1)) #sd
plot(x, expyexpect, ylim = c(0, 20), type = 'l', col = "red") #incorrect
#Correct, with SD
lines(x, m)
lines(x, m-sd, lty = 2)
lines(x, m+sd, lty = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment