R/logistic_scatter.R

Defines functions logistic_scatter loess_plot logit

Documented in loess_plot logistic_scatter logit

#' Logistic Scatter
#'
#' This function takes a list of predictors as inputs and outputs a scatterplot matrix
#' to indicate the functional form of logit(p).
#'
#'@param data This is the data frame you will use to crush the enemy
#'@param response A binary response variable. You know what to do...
#'@param ... continuous predictors. Do not pollute my graph with discrete garbage.
#'@param smoothing Loess is used to estimate logit(p) so you can choose the smoothness
#'@param jitter Sometimes your points overplot and you don't want that to happen. Set to true to jitter 'em!
#'@export
#'@examples
#'data %>% logistic_scatter(response, predictor_1, predictor_2, smoothing = 0.5, jitter=TRUE)

logistic_scatter <- function(data, response, ..., smoothing = 0.7, jitter=FALSE){
  predictors <- map(enexprs(...), function(x){return(expr(`$`(!!data, !!(x))))})
  # subtract one because as.numeric seems to make the levels 1 and 2.
  response <- expr(`$`(!!enexpr(data), !!enexpr(response)))
  graph_list <- map(predictors, loess_plot, response = response, span = smoothing, jitter=jitter)
  names(graph_list) <- as.character(eval(enexprs(...)))
}

#'This is a LOESS plotting function. Pay it no mind.
#'@param predictor a predictor
#'@param response spoiler: a response
#'@param span how smooth you want that alpha to be, pham?
#'@param jitter want it jittered?

loess_plot <- function(predictor, response, span, jitter){
  response <- as.numeric(eval(response)) - 1
  loess.mod <- loess(response ~ eval(predictor), span = span)
  loess.pred <- predict(loess.mod)
  prob <- pmax(pmin(loess.pred, 0.9999), 0.0001)
  logit.loess.pred <- logit(prob)
  if(jitter == FALSE){
    return(ggplot(NULL,aes(x = eval(predictor), y = logit.loess.pred)) + geom_point() +
             labs(y = "Estimated logit(p)", x = predictor))
  }
  else{
    return(ggplot(NULL,aes(x = predictor, y = logit.loess.pred)) + geom_point(position = "jitter") +
             labs(y = "Estimated logit(p)", x = predictor))
  }

}

#' Logit Function
#' Takes probability and makes it into log odds
#' @param p estimated probability

logit <- function(p){
  log(p/(1-p))
}
KThompson0308/RUtilities documentation built on Dec. 8, 2019, 8:30 a.m.