File: logit.R

package info (click to toggle)
gtools 3.9.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 748 kB
  • sloc: ansic: 190; makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,356 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#' Generalized logit and inverse logit function
#'
#' Compute generalized logit and generalized inverse logit functions.
#'
#'
#' The generalized logit function takes values on [min, max] and transforms
#' them to span [-Inf,Inf] it is defined as:
#'
#' \deqn{y = log(\frac{p}{(1-p)})}{y = log(p/(1-p))}
#'
#' where
#'
#' \deqn{p=\frac{(x-min)}{(max-min)}}{p=(x-min)/(max-min)}
#'
#' The generalized inverse logit function provides the inverse transformation:
#'
#' \deqn{x = p' (max-min) + min}{x = p * (max-min) + min}
#'
#' where
#'
#' \deqn{p'=\frac{exp(y)}{(1+exp(y))}}{exp(y)/(1+exp(y))}
#'
#' @aliases logit inv.logit
#' @param x value(s) to be transformed
#' @param min Lower end of logit interval
#' @param max Upper end of logit interval
#' @return Transformed value(s).
#' @author Gregory R. Warnes \email{greg@@warnes.net}
#' @seealso \code{\link[car]{logit}}
#' @keywords math
#' @examples
#'
#'
#' x <- seq(0, 10, by = 0.25)
#' xt <- logit(x, min = 0, max = 10)
#' cbind(x, xt)
#'
#' y <- inv.logit(xt, min = 0, max = 10)
#' cbind(x, xt, y)
#' @export
logit <- function(x, min = 0, max = 1) {
  p <- (x - min) / (max - min)
  log(p / (1 - p))
}


#' @rdname logit
#' @export
inv.logit <- function(x, min = 0, max = 1) {
  p <- exp(x) / (1 + exp(x))
  p <- ifelse(is.na(p) & !is.na(x), 1, p) # fix problems with +Inf
  p * (max - min) + min
}