Proč nedokážu přečíst váš kód?

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

Slovesa dplyr

select() vybírá sloupce

filter() filtruje řádky

Introduction to Writing Functions in R

Název funkce by měl obsahovat sloveso

  • get
  • calculate (nebo jen calc)
  • run
  • process
  • import
  • clean
  • tidy
  • draw
Introduction to Writing Functions in R

lm() má nevhodný název

  • Zkratky nejsou samovysvětlující
  • Neobsahuje sloveso
  • Existuje mnoho různých lineárních modelů

Lepší název by byl run_linear_regression()

Introduction to Writing Functions in R

Čitelnost vs. rychlost psaní

  • Porozumění kódu >> psaní kódu
Introduction to Writing Functions in R

Čitelnost vs. rychlost psaní

  • Porozumění kódu >> psaní kódu
  • Editory kódu mají automatické doplňování

datacamp-autocomplete.png

Introduction to Writing Functions in R

Čitelnost vs. rychlost psaní

  • Porozumění kódu >> psaní kódu
  • Editory kódu mají automatické doplňování
  • Běžné funkce lze aliasovat
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
Introduction to Writing Functions in R

Argumenty funkce 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, ...)
Introduction to Writing Functions in R

Typy argumentů

  • Datové argumenty: co se počítá
  • Argumenty nastavení: jak se výpočet provede
args(cor)
function (x, y = NULL, use = "everything", 
  method = c("pearson", "kendall", "spearman"))
Introduction to Writing Functions in R

Datové argumenty musí předcházet argumentům nastavení

Toto nebude fungovat

data %>%
  lm(formula)

protože datový argument není na prvním místě.

Introduction to Writing Functions in R

Upravená funkce pro lineární regresi

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
Introduction to Writing Functions in R

Pojďme si procvičit!

Introduction to Writing Functions in R

Preparing Video For Download...