Skip to content

Instantly share code, notes, and snippets.

@CoryMcCartan
Last active July 30, 2025 15:19
Show Gist options
  • Select an option

  • Save CoryMcCartan/220701121c3f0520c2878e0010ced26b to your computer and use it in GitHub Desktop.

Select an option

Save CoryMcCartan/220701121c3f0520c2878e0010ced26b to your computer and use it in GitHub Desktop.
Logit-shift a vector to have a specified mean
#' Logit-shift a vector to have a specified mean
#'
#' Finds and applies a shift on the logit scale so that a vector has a chosen mean.
#'
#' @param x The vector to shift
#' @param target The target mean, a single value between 0 and 1
#'
#' @returns A new vector with length matching `x`
#'
#' @references
#' Rosenman, E. T., McCartan, C., & Olivella, S. (2023). Recalibration of Predicted
#' Probabilities Using the "Logit Shift": Why Does It Work, and When Can It Be
#' Expected to Work Well?. *Political Analysis*, 31(4), 651-661.
logit_shift = function(x, target) {
diff = qlogis(mean(x)) - qlogis(target)
bounds = if (diff > 0) c(-2*diff, 0) else c(0, -2*diff)
shift = uniroot(function(s) mean(plogis(qlogis(x) + s)) - target, bounds)$root
plogis(qlogis(x) + shift)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment