13  Three Dots

13.1 Function with ... argument

  • The advantage of ... argument
    • to extend the functionality of another function
    • when the number of arguments passed to the function cannot be known in advance
    • arguments comming after the ... must be named explicitly and cannot be partially matched or matched positionally (named matching)
  • You can capture variables and values passed under ... arguments as list(...)

13.2 Data

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

13.3 Using function arguments: Option 1

The earlier version of the function

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)
}

fn_mean(A, na_rm = TRUE)
[1] 14.75

13.4 Using function arguments: Option 2

A new version of the function by passing na_rm argument to other functions

Code
fn_mean = function(x, na_rm = FALSE) {
    xn = ifelse(na_rm, length(na.omit(x)), length(x))
    xsum = sum(x, na.rm = na_rm)
    xmean = xsum/xn
    return(xmean)
}

fn_mean(A, na_rm = TRUE)
[1] 14.75

13.5 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?

13.6 Use ... arguments

A 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.

Code
fn_mean = function(x, ...) {
    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
    return(xmean)
}

fn_mean(A, na.rm = TRUE)
[1] 14.75

13.7 Function with **kwargs arguments

Three 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.

Code
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)