Waarden retourneren uit functies

Introductie tot functies schrijven in R

Richie Cotton

Data Evangelist at DataCamp

Een eenvoudige somfunctie

simple_sum <- function(x) {

if(anyNA(x)) {
return(NA)
}
total <- 0 for(value in x) { total <- total + value } total }
simple_sum(c(0, 1, 3, 6, NA, 7))
NA
Introductie tot functies schrijven in R

Meetkundig gemiddelde (opnieuw)

calc_geometric_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)
  if(any(is_non_positive(x), na.rm = TRUE)) {
    stop("x contains non-positive values, so the geometric mean makes no sense.")
  }
  na.rm <- coerce_to(use_first(na.rm), "logical")
  x %>%
    log() %>%
    mean(na.rm = na.rm) %>%
    exp()
}
Introductie tot functies schrijven in R

NaN retourneren met een waarschuwing

calc_geometric_mean <- function(x, na.rm = FALSE) {
  assert_is_numeric(x)
  if(any(is_non_positive(x), na.rm = TRUE)) {

warning("x contains non-positive values, so the geometric mean makes no sense.") return(NaN)
} na.rm <- coerce_to(use_first(na.rm), "logical") x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
Introductie tot functies schrijven in R

Redenen om vroeg te retourneren

  1. Je kent het antwoord al.
  2. De input is een randgeval.
Introductie tot functies schrijven in R

De returnwaarde verbergen

simple_sum <- function(x) {
  if(anyNA(x)) {
    return(NA)
  }
  total <- 0
  for(value in x) {
    total <- total + value
  }
  total
}
simple_sum(c(0, 1, 3, 6, 2, 7))
19
Introductie tot functies schrijven in R

De returnwaarde verbergen

simple_sum <- function(x) {
  if(anyNA(x)) {
    return(NA)
  }
  total <- 0
  for(value in x) {
    total <- total + value
  }

invisible(total)
}
simple_sum(c(0, 1, 3, 6, 2, 7))


Introductie tot functies schrijven in R

Veel plots retourneren onzichtbaar iets

ggplot(snake_river_visits, aes(n_visits)) +
  geom_histogram(binwidth = 10)

Een histogram van bezoeken aan Snake River. De verdeling is rechts-scheef; de meeste mensen zitten in de linkerbalk met minder dan 5 bezoeken per jaar. De grootste waarde is meer dan 300 bezoeken per jaar.

Introductie tot functies schrijven in R

Veel plots retourneren onzichtbaar iets

srv_hist <- ggplot(snake_river_visits, aes(n_visits)) +
  geom_histogram(binwidth = 10)
str(srv_hist, max.level = 0)
List of 9
 - attr(*, "class")= chr [1:2] "gg" "ggplot"

Hetzelfde histogram van Snake River-bezoeken van de vorige slide wordt opnieuw getoond.

Introductie tot functies schrijven in R

Laten we oefenen!

Introductie tot functies schrijven in R

Preparing Video For Download...