R/sigmoid.R

# The 'sigmoid' function
# Written by Kevin Potter
# email: kevin.w.potter@gmail.com
# Please email me directly if you
# have any questions or comments
# Last updated 2018-10-31

# Table of contents
# 1) sigmoid        | No test necessary

###
### 1)
###

#' Apply the Logistic or Logit functions
#'
#' Applies the logistic function to a vector of
#' continuous values, or if specified, applies
#' the logit (log-odds) function to a vector of
#' probabilities.
#'
#' @param x Either a vector of unbounded continuous values, or
#'   if \code{prob} is \code{TRUE}, a vector of probabilities.
#' @param prob Logical; if \code{TRUE}, assumes \code{x} is a
#'   vector of probabilities and applies the logit function.
#'
#' @return A transformed vector, either the result of the logistic
#'   function, or if \code{prob} is \code{TRUE}, the result of the
#'   logit function.
#'
#' @export
#' @examples
#' # Logistic function
#' sigmoid( 0 )
#' sigmoid( -1.098612 ); sigmoid( 1.098612 );
#' sigmoid( -Inf ); sigmoid( Inf )
#' # Logit function
#' sigmoid( 0, T )
#' sigmoid( .25, T ); sigmoid( .75, T )
#' sigmoid( 0, T ); sigmoid( 1, T )

sigmoid = function( x, prob = F ) {

  # If inputs are probabilities
  if ( prob ) {

    # Check bounds
    if ( all( x >= 0 | x <= 1 ) ) {
      # Compute the log-odds
      out = log( x/(1-x) )
    } else {
      # Return an error
      stop( 'Input must be vector of probabilities',
            call. = F )
    }

  } else {

    # Compute the logistic function
    out = 1/( 1 + exp( -x ) )

  }

  return( out )
}
rettopnivek/binclass documentation built on May 13, 2019, 4:46 p.m.