23  R: Function as a String

23.1 Function as a character/string

Code
fn_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)
}

23.2 Data

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

23.3 Function call: Option 1

Code
do.call("fn_Mean", list(A, na.rm = T))
$n
[1] 4

$AM
[1] 14.75

$GM
[1] 14.5938

$HM
[1] 14.44126

23.4 Function call: Option 2

Code
fn_call = function(f, arg, ...) get(f)(arg, ...)

fn_call("fn_Mean", A, na.rm = T)
$n
[1] 4

$AM
[1] 14.75

$GM
[1] 14.5938

$HM
[1] 14.44126
Code
fn_call("sd", A, na.rm = T)
[1] 2.5

23.5 Function call: Option 3

Code
fn_list = list("fn_Mean", "mean", "median", "sd", "var")

f = match.fun(fn_list[[3]])

f(A, na.rm = TRUE)
[1] 14.5
Code
sd(A, na.rm = TRUE)
[1] 2.5