Default arguments

Introduzione alla scrittura di funzioni in R

Richie Cotton

Data Evangelist at DataCamp

toss_coin() troubles

toss_coin <- function(n_flips, p_head) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}

Set the default in the signature

toss_coin <- function(n_flips, p_head = 0.5) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}
Introduzione alla scrittura di funzioni in R

A template with defaults

my_fun <- function(data_arg1, data_arg2, detail_arg1 = default1) {
  # Do something
}
Introduzione alla scrittura di funzioni in R

Other types of default

args(median)
function (x, na.rm = FALSE, ...)
library(jsonlite)
args(fromJSON)
function (txt, simplifyVector = TRUE, simplifyDataFrame = simplifyVector, 
    simplifyMatrix = simplifyVector, flatten = FALSE, ...)
Introduzione alla scrittura di funzioni in R

NULL defaults

By convention, this means

The function will do some special handling of this argument. Please read the docs.

args(set.seed)
function (seed, kind = NULL, normal.kind = NULL)
Introduzione alla scrittura di funzioni in R

Categorical defaults

  1. Pass a character vector in the signature.
  2. Call match.arg() in the body.
args(prop.test)
function (x, n, p = NULL, alternative = c("two.sided", "less", "greater"), 
  conf.level = 0.95, correct = TRUE)

Inside the body

alternative <- match.arg(alternative)
Introduzione alla scrittura di funzioni in R

Cutting a vector by quantile

cut_by_quantile <- function(x, n, na.rm, labels, interval_type) {
  probs <- seq(0, 1, length.out = n + 1)
  quantiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
  right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
  cut(x, quantiles, labels = labels, right = right, include.lowest = TRUE)
}
  • x: A numeric vector to cut
  • n: The number of categories to cut x into
  • na.rm: Should missing value be removed?
  • labels: Character labels for the categories
  • interval_type: Should ranges be open on the left or right?
Introduzione alla scrittura di funzioni in R

Cat heart weights

A strip plot of cat's heart weights. The range is from 3 to 20 grams.

quantile(cats$Hwt)
    0%    25%    50%    75%   100% 
 6.300  8.950 10.100 12.125 20.500
1 data(cats, package = "MASS")
Introduzione alla scrittura di funzioni in R

Cutting by quantile

The strip plot from the previous slide has been given color, with red points on the left, then green, then turquoise, then purple on the right.

cut(x, quantile(x))
Introduzione alla scrittura di funzioni in R

Let's practice!

Introduzione alla scrittura di funzioni in R

Preparing Video For Download...