11  Multiple arguments

11.1 Function with two arguments

  • Function with mandatory and default arguments
Code
fn_mean = function(x, na_rm = FALSE) {
    if (na_rm)
        x = na.omit(x)
    xn = length(x)
    xsum = sum(x)
    xmean = xsum/xn
    return(xmean)
}

11.2 Data

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

B = c(NA, 12, 15, 14, 18)

11.3 Call with mandatory argument

Code
fn_mean(A)
[1] 14
Code
fn_mean(B)
[1] NA

11.4 Call with mandatory and default arguments

Code
fn_mean(B, na_rm = TRUE)
[1] 14.75

11.5 Function with two arguments

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



# Example usage:
A = np.array([11, 12, np.nan, 14, 15])
fn_mean(A, na_rm=True)
fn_mean(A, na_rm=False)