Chapter 19 Functions

Introducyion

When should you write a function?

## # A tibble: 10 × 4
##        a      b     c     d
##    <dbl>  <dbl> <dbl> <dbl>
##  1 0.332 0.153  0.782 1    
##  2 0.765 0      0.473 0.519
##  3 1     0.0651 0.498 0.448
##  4 0     0.311  0.943 0.511
##  5 0.809 0.573  0.373 0.168
##  6 0.831 0.260  0     0.308
##  7 0.516 0.143  1     0    
##  8 0.524 0.0255 0.210 0.256
##  9 0.519 0.0472 0.708 0.575
## 10 0.424 1      0.253 0.522

Functions are for humans and computers

Conditional execution

## Value is positive
## [1] 3
## Warning in detect_sign(.): Value is not positive, but it can be accepted
## [1] 0
## Value is negative, the function must stop
## [1] -1

Function arguments

## starting httpd help server ... done
##  [1]   1   2   3   4   5   6   7   8   9  10 100  NA
## [1] NA
## [1] 6
## [1] 14.09091
## [1] 14.09091
## [1] NA
## [1] 6

two types of function

  • one that takes a vector as the input
  • another that takes a data frame as the input