28  R: Debugging a Function

28.1 Debugging a Function

  • The following set of functions computes AM, GM and HM.

  • Copy and paste the following function in an R script named fn_Debug.R in your current working directory

  • Source the function using the following script: source('fn_Debug.R')

  • Note that this script is for demonstration purpose only. All functions are unnecessarily extended; this practice is not recommended.

  • We will use fn_Mean to explore dubugging options.

  • An optimal function prototype Mean is also shown.

  • Debugging procedures are explored in (1) console and (2) RStudio environments

Code
# Functions to calculate AM, GM, HM
# _______________________________________________________________________________

fn_n = function(x, na.rm = FALSE) {
    out = ifelse(na.rm, length(na.omit(x)), length(x))
    return(out)
}

fn_sum = function(x, ...) {
    out = sum(x, ...)
    return(out)
}

fn_prod = function(x, ...) {
    out = prod(x, ...)
    return(out)
}

fn_suminv = function(x, ...) {
    out = sum(1/x, ...)
    return(out)
}

fn_AM = function(x, ...) {
    sx = fn_sum(x, ...)
    nx = fn_n(x, ...)
    out = sx/nx
    return(out)
}

fn_GM = function(x, ...) {
    px = fn_prod(x, ...)
    nx = fn_n(x, ...)
    out = px^(1/nx)
    return(out)
}

fn_HM = function(x, ...) {
    isx = fn_suminv(x, ...)
    nx = fn_n(x, ...)
    out = nx/isx
    return(out)
}

# _______________________________________________________________________________
# fn_Mean

fn_Mean = function(x, ...) {
    n = fn_n(x, ...)
    AM = fn_AM(x, ...)
    GM = fn_GM(x, ...)
    HM = fn_HM(x, ...)
    Mean = list(n = n, AM = AM, GM = GM, HM = HM)
    return(Mean)
}
# _______________________________________________________________________________
# Optimal function

Mean = function(x, ...) {
    fn_n = function(x, na.rm = FALSE) ifelse(na.rm, length(na.omit(x)), length(x))
    n = fn_n(x, ...)
    AM = mean(x, ...)
    GM = exp(mean(log(x), ...))
    HM = 1/mean(1/x, ...)
    Mean = list(n = n, AM = AM, GM = GM, HM = HM)
    return(Mean)
}
# _______________________________________________________________________________