15 Local assignment
In R and Python, arguments are passed by value
15.1 Passing by value
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):
= kwargs.get('na_rm', None)
na_rm
if na_rm:
= x[~np.isnan(x)]
x
= y**2
y
= len(x)
xn = np.sum(x)
xsum = xsum / xn
xmean return xmean
# Example usage:
= np.array([11, 12, np.nan, 14, 15])
A = 5
y =y, na_rm=True)
fn_mean(A, y y