15  Local assignment

In R and Python, arguments are passed by value

15.1 Passing by value

Code
fn_mean = function(x, y, ...) {

    fn_n = function(x, na.rm = FALSE) ifelse(na.rm, length(na.omit(x)), length(x))
    xn = fn_n(x, ...)
    xsum = sum(x, ...)
    xmean = xsum/xn

    y = y^2
    return(list(y = y, xmean = xmean))

}

15.2 Data

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

15.3 Function call 1

Code
y = 5

fn_mean(A, y = y, na.rm = TRUE)
$y
[1] 25

$xmean
[1] 14.75
Code
y
[1] 5

15.4 Function call 2

Note the function arguments are mandatory here; there is no default value of y

The following run will show an error if the mandatory argument is missing

Code
fn_mean(A, na.rm = TRUE)
Error in fn_mean(A, na.rm = TRUE): argument "y" is missing, with no default

15.5 Passing by value

Code
def fn_mean(x, y, **kwargs):
    
    na_rm = kwargs.get('na_rm', None)
    
    if na_rm:
        x = x[~np.isnan(x)]
    
    y = y**2
        
    xn = len(x)
    xsum = np.sum(x)
    xmean = xsum / xn
    return xmean


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