Skip to content

Instantly share code, notes, and snippets.

@kgori
Created November 27, 2018 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgori/f21e0133411e3244289d53551f427048 to your computer and use it in GitHub Desktop.
Save kgori/f21e0133411e3244289d53551f427048 to your computer and use it in GitHub Desktop.
Convert regression line coefficient and intercept of standardised variables back to the original scale
# Standardisation formula
z <- function(x) (x - mean(x)) / sd(x)
#' Convert regression parameters obtained from standardised variables
#' back to the scale of the original data.
#'
#' For a regression y ~ x*, where x* denotes the standardised form of x:
#' Result: y = m(x*) + c
#' Transformed: y = (m / sd(x))(x) + (c - (m*mean(x)/sd(x))
#'
#' For a regression y* ~ x*, where (x*, y*) are the standardised forms of (x, y):
#' Result: y* = m(x*) + c
#' Transformed: y = (m * sd(y) / sd(x))(x) + sd(y)(c - m * mean(x) / sd(x)) + mean(y)
#'
#' @param m - the slope parameter of the regression
#' @param c - the intercept of the regression
#' @param x - values of x on the original scale. It is assumed that at least the
#' predictors (x) were standardised. If responses (y) were also standardised,
#' the original values must be passed through parameter `y`.
#' @param y - values of y on the original scale. If given (not NULL) it is assumed
#' that both the responses (y) and predictors (x) were standardised
transform <- function(m, c, x, y = NULL) {
slope <- m / sd(x)
intercept <- c - m * mean(x) / sd(x)
if (!is.null(y)) {
slope <- slope * sd(y)
intercept <- sd(y) * intercept + mean(y)
}
list(m = slope, c = intercept)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment