Standaardargumenten

Introductie tot functies schrijven in R

Richie Cotton

Data Evangelist at DataCamp

Problemen met toss_coin()

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

Stel de standaardwaarde in de handtekening in

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)
}
Introductie tot functies schrijven in R

Een sjabloon met defaults

my_fun <- function(data_arg1, data_arg2, detail_arg1 = default1) {
  # Do something
}
Introductie tot functies schrijven in R

Andere typen defaults

args(median)
function (x, na.rm = FALSE, ...)
library(jsonlite)
args(fromJSON)
function (txt, simplifyVector = TRUE, simplifyDataFrame = simplifyVector, 
    simplifyMatrix = simplifyVector, flatten = FALSE, ...)
Introductie tot functies schrijven in R

NULL-standaarden

Volgens conventie betekent dit:

De functie behandelt dit argument speciaal. Lees de documentatie.

args(set.seed)
function (seed, kind = NULL, normal.kind = NULL)
Introductie tot functies schrijven in R

Categorische defaults

  1. Geef in de handtekening een karaktervector op.
  2. Roep match.arg() aan in de body.
args(prop.test)
function (x, n, p = NULL, alternative = c("two.sided", "less", "greater"), 
  conf.level = 0.95, correct = TRUE)

In de body

alternative <- match.arg(alternative)
Introductie tot functies schrijven in R

Een vector in kwantielen opdelen

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: Een numerieke vector om te categoriseren
  • n: Aantal categorieën om x in te delen
  • na.rm: Moeten missende waarden worden verwijderd?
  • labels: Tekstlabels voor de categorieën
  • interval_type: Moeten intervallen links of rechts open zijn?
Introductie tot functies schrijven in R

Hartgewichten van katten

Een stripplot van hartgewichten van katten. Het bereik is 3–20 gram.

quantile(cats$Hwt)
    0%    25%    50%    75%   100% 
 6.300  8.950 10.100 12.125 20.500
1 data(cats, package = "MASS")
Introductie tot functies schrijven in R

Opdelen op kwantielen

De stripplot van de vorige slide heeft nu kleur: links rood, dan groen, dan turquoise, en rechts paars.

cut(x, quantile(x))
Introductie tot functies schrijven in R

Laten we oefenen!

Introductie tot functies schrijven in R

Preparing Video For Download...