12  Arguments Matching

12.1 Arguments matching

  • Matched by argument names

  • Matched by argument positions

  • Matched by a mix of argument names and positions

  • Partial matching is possible

  • Order of argument matching

    • Check for the exact match
    • Check for the partial match
    • Check for the positional match

12.2 Function

Code
fn_mean = function(x, na_rm = FALSE, var_name = "X") {
    if (na_rm)
        x = na.omit(x)
    xn = length(x)
    xsum = sum(x)
    xmean = xsum/xn
    cat("Mean", var_name, "is:", xmean, "\n")
    return(xmean)
}

12.3 Data

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

12.4 Name matching

Code
fn_mean(x = A, na_rm = TRUE, var_name = "bacterial count")
Mean bacterial count is: 14.75 
[1] 14.75

12.5 Position matching

Code
fn_mean(A, TRUE, "bacterial count")
Mean bacterial count is: 14.75 
[1] 14.75

12.6 Exact name matching

Code
fn_mean(var_name = "bacterial count", x = A, na_rm = TRUE)
Mean bacterial count is: 14.75 
[1] 14.75

12.7 Partial name matching

Code
fn_mean(va = "bacterial count", x = A, na = TRUE)
Mean bacterial count is: 14.75 
[1] 14.75

12.8 Exact name and position matching

Code
fn_mean(var_name = "bacterial count", A, TRUE)
Mean bacterial count is: 14.75 
[1] 14.75

12.9 Partial name and position matching

Code
fn_mean(va = "bacterial count", x = A, na_rm = TRUE)
Mean bacterial count is: 14.75 
[1] 14.75

12.10 Error

Code
fn_mean(va = "bacterial count", TRUE, A)
Error in if (na_rm) x = na.omit(x): the condition has length > 1

12.11 Function call

Python does not perform partial matching of function arguments like R does. You need to provide the exact argument name when calling a function. Python allows positional mathcing and exact name matching. Arguments not matched exactly will show error.

Code
def fn_mean(x, na_rm=False, var_name='X'):
    
    if na_rm:
        x = x[~np.isnan(x)]
        
    xn = len(x)
    xsum = np.sum(x)
    xmean = xsum / xn
    
    print(f'\nMean {var_name} is: {xmean}')
    return xmean

A = np.array([11, 12, np.nan, 14, 15])


fn_mean(x = A, na_rm = True, var_name = "bacterial count")

fn_mean(A, True, "bacterial count")

fn_mean(var_name = "bacterial count", x = A, na_rm = True)