Skip to content

Instantly share code, notes, and snippets.

@dreidpath
Created October 20, 2015 03:30
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 dreidpath/6ee2bb95c6010cff3874 to your computer and use it in GitHub Desktop.
Save dreidpath/6ee2bb95c6010cff3874 to your computer and use it in GitHub Desktop.
Take an R lm model expressed in terms of y ~ x. Provided values for y, return "estimated" x.
returnXinY <- function(lm_model, y_values){
# This function takes a lm model expressed in terms of y ~ x, and values for y, and returns x
# Given a model of the form y ~ beta.x + alpha, then given values for y, return x = (y-alpha)/beta
# Crazy I know, but there you have it.
#
if(class(lm_model) != "lm"){
stop("This function requires a lm mode with a single predictor variable (y ~x)")
}
if(length(unlist(strsplit(toString(lm_model$call[2][[1]]), " "))) > 3){
stop("This function only works with a lm model with a single predictor variable (y ~x)")
}
lm_coefs <- coef(lm_model)
x_values <- (y_values-lm_coefs[1])/lm_coefs[2]
return(x_values)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment