Code
A = c(NA, 12, 15, 14, 18)
Function with ... argument... argument
... must be named explicitly and cannot be partially matched or matched positionally (named matching)... arguments as list(...)
A = c(NA, 12, 15, 14, 18)The earlier version of the function
A new version of the function by passing na_rm argument to other functions
help(sum)
Description
sum returns the sum of all the values present in its arguments.
Usage
sum(..., na.rm = FALSE)
Arguments
... numeric or complex or logical vectors.
na.rm logical. Should missing values (including NaN) be removed?
... argumentsA modified function using ... as arguments. Note the function can be called without any additional arguments.
For example, the fn_mean can be called as fn_mean(A, na.rm = TRUE) and fn_mean(A) without any error.
Function with **kwargs argumentsThree dots (also called ellipsis) in Python is placeholder for interpreter to ignore and do nothing. This is equivalent to the pass keyword. Hence, three dots does not have the same meaning as in R. The **kwargs in function allows accepting multiple named arguments in Python.
Note the function can be called without any additional **kwargs arguments.
For example, the fn_mean can be called as fn_mean(A, na_rm = True) and fn_mean(A) without any error.
import numpy as np
def fn_mean(x, **kwargs):
na_rm = kwargs.get('na_rm', None)
if na_rm:
x = x[~np.isnan(x)]
xn = len(x)
xsum = np.sum(x)
xmean = xsum / xn
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)