22  R: Functions as an Argument

22.1 Functions as an argument

Code
fn_n = function(x, na.rm = FALSE) ifelse(na.rm, length(na.omit(x)), length(x))

fn_sum = function(x, ...) sum(x, ...)

fn_prod = function(x, ...) prod(x, ...)

fn_suminv = function(x, ...) sum(1/x, ...)

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

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

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


# Function Summary

fn_summary = function(x, FUN = fn_AM, ...) {

    n = fn_n(x, ...)

    y = FUN(x, ...)

    out = list(n = n, out = y)

    return(out)

}

22.2 Data

Code
A = c(NA, 12, 15, 14, 18)

22.3 Function call 1

Code
fn_summary(A, FUN = fn_AM, na.rm = TRUE)
$n
[1] 4

$out
[1] 14.75

22.4 Function call 2

Code
fn_summary(A, FUN = median, na.rm = TRUE)
$n
[1] 4

$out
[1] 14.5