Návratové hodnoty funkcí

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

Jednoduchá funkce součtu

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

Geometrické průměry znovu

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

Vrácení NaN s varováním

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

Důvody pro předčasný návrat

  1. Odpověď již znáte.
  2. Vstup je hraniční případ.
Introduction to Writing Functions in R

Skrytí návratové hodnoty

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

Skrytí návratové hodnoty

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))


Introduction to Writing Functions in R

Mnoho grafů neviditelně vrací hodnoty

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

Histogram návštěv řeky Snake. Rozdělení je pravostranně zešikmené – většina hodnot je v levém sloupci (méně než 5 návštěv ročně). Nejvyšší hodnota přesahuje 300 návštěv ročně.

Introduction to Writing Functions in R

Mnoho grafů neviditelně vrací hodnoty

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"

Stejný histogram návštěv řeky Snake jako na předchozím snímku.

Introduction to Writing Functions in R

Pojďme procvičovat!

Introduction to Writing Functions in R

Preparing Video For Download...