Base R’s built-in logit and expit functions

functions

plogis() and qlogis()

Quang Nguyen https://github.com/qntkhvn
July 21, 2022

I did not know there were built-in functions in base R for calculating the logit and expit… until today.

First, recall that the logit function for any \(x \in (0,1)\) is

\[ logit(x) = log\left(\frac{x}{1-x}\right). \]

When working with categorical data, we can think of \(x\) here as a probability of success. Hence the logit of \(x\) is the log odds ratio of the probability of success over the probability of failure.

To obtain the log odds for a given probability in R, we could do…

prob <- 0.2
log(prob / (1 - prob))
[1] -1.386294

or simply with qlogis(), as I just discovered…

qlogis(prob)
[1] -1.386294

On the other hand, the expit function for any \(x \in \mathbb{R}\) is

\[ expit(x) = \frac{e^x}{1+e^x}. \]

The expit maps the real numbers to \((0, 1)\). It is also known as the inverse logit function, or the sigmoid function, which is very popular in deep nets.

You’ve probably done this type of conversion before, in a logistic regression setting. When making a prediction after fitting a model and you’re being ask to give a probability, this is exactly what you would do.

Just as before, we could do it “by hand”…

logit <- 0.3
exp(logit) / (1 + exp(logit))
[1] 0.5744425

or with a more simple function, plogis()…

plogis(logit)
[1] 0.5744425

From my personal experience, I have written down the full formula for both logit and expit many times and forgotten a parenthesis here and there every so often. This is where plogis and qlogis will come in handy. More simple. Less code writing. And no more errors related to ()’s.

Citation

For attribution, please cite this work as

Nguyen (2022, July 21). The Q: Base R's built-in logit and expit functions. Retrieved from https://qntkhvn.netlify.app/posts/2022-07-21-logit-expit/

BibTeX citation

@misc{nguyen2022base,
  author = {Nguyen, Quang},
  title = {The Q: Base R's built-in logit and expit functions},
  url = {https://qntkhvn.netlify.app/posts/2022-07-21-logit-expit/},
  year = {2022}
}