Waarom kan ik je code niet lezen?

Introductie tot functies schrijven in R

Richie Cotton

Data Evangelist at DataCamp

dplyr-werkwoorden

select() selecteert kolommen

filter() filtert rijen

Introductie tot functies schrijven in R

Functienamen moeten een werkwoord bevatten

  • ophalen
  • berekenen (of kort: calc)
  • draaien
  • verwerken
  • importeren
  • opschonen
  • tidy maken
  • tekenen
Introductie tot functies schrijven in R

lm() is slecht benoemd

  • Acronieten leggen zichzelf niet uit
  • Er staat geen werkwoord in
  • Er zijn veel soorten lineaire modellen

Een betere naam is run_linear_regression()

Introductie tot functies schrijven in R

Leesbaarheid vs. typegemak

  • Code snappen >> code typen
Introductie tot functies schrijven in R

Leesbaarheid vs. typegemak

  • Code snappen >> code typen
  • Editors hebben autocompletion

Datacamp-autocomplete.png

Introductie tot functies schrijven in R

Leesbaarheid vs. typegemak

  • Code snappen >> code typen
  • Editors hebben autocompletion
  • Je kunt veelgebruikte functies aliassen
h <- head
data(cats, package = "MASS")
h(cats)
  Sex Bwt Hwt
1   F 2.0 7.0
2   F 2.0 7.4
3   F 2.0 9.5
4   F 2.1 7.2
5   F 2.1 7.3
6   F 2.1 7.6
Introductie tot functies schrijven in R

Argumenten van lm()

args(lm)
function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...)
Introductie tot functies schrijven in R

Soorten argumenten

  • Data-argumenten: waarop je rekent
  • Detailargumenten: hoe je rekent
args(cor)
function (x, y = NULL, use = "everything", 
  method = c("pearson", "kendall", "spearman"))
Introductie tot functies schrijven in R

Data- vóór detailargumenten

Dit werkt niet

data %>%
  lm(formula)

omdat het data-argument niet eerst staat.

Introductie tot functies schrijven in R

Onze aangepaste functie voor lineaire regressie

run_linear_regression <- function(data, formula) {
  lm(formula, data)
}
cats %>% 
  run_linear_regression(Hwt ~ Bet + Sex)
Call:
lm(formula = formula, data = data)

Coefficients:
(Intercept)          Bwt         SexM  
    -0.4150       4.0758      -0.0821
Introductie tot functies schrijven in R

Laten we oefenen!

Introductie tot functies schrijven in R

Preparing Video For Download...