Passing arguments between functions

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

Calculating the geometric mean

x %>%
  log() %>%
  mean() %>%
  exp()
Introduction to Writing Functions in R

Wrapping this in a function

calc_geometric_mean <- function(x) {
  x %>%
    log() %>%
    mean() %>%
    exp()
}
Introduction to Writing Functions in R

Handling missing values

calc_geometric_mean <- function(x, na.rm = FALSE) {
  x %>%
    log() %>%
    mean(na.rm = na.rm) %>%
    exp()
}
Introduction to Writing Functions in R

Using ...

calc_geometric_mean <- function(x, ...) {
  x %>%
    log() %>%
    mean(...) %>%
    exp()
}
Introduction to Writing Functions in R

The tradeoff

Benefits

  • Less typing for you
  • No need to match signatures

Drawbacks

  • You need to trust the inner function
  • The interface is not as obvious to users
Introduction to Writing Functions in R

Let's practice!

Introduction to Writing Functions in R

Preparing Video For Download...