Fonksiyonlardan değer döndürme

R'de Fonksiyon Yazmaya Giriş

Richie Cotton

Data Evangelist at DataCamp

Basit bir toplam fonksiyonu

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
R'de Fonksiyon Yazmaya Giriş

Geometrik ortalama yine

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()
}
R'de Fonksiyon Yazmaya Giriş

Uyarıyla NaN döndürme

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() }
R'de Fonksiyon Yazmaya Giriş

Erken döndürme nedenleri

  1. Yanıtı zaten biliyorsunuz.
  2. Girdi uç bir durumdur.
R'de Fonksiyon Yazmaya Giriş

Dönüş değerini gizleme

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
R'de Fonksiyon Yazmaya Giriş

Dönüş değerini gizleme

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


R'de Fonksiyon Yazmaya Giriş

Birçok grafik görünmez değer döndürür

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

Snake River ziyaretlerinin histogramı. Dağılım sağa çarpık; çoğu kişi yılda 5 ziyaretten az olan soldaki çubukta. En büyük değer yılda 300’ün üzerinde.

R'de Fonksiyon Yazmaya Giriş

Birçok grafik görünmez değer döndürür

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"

Önceki slayttaki Snake River ziyaretlerinin aynı histogramı tekrar gösteriliyor.

R'de Fonksiyon Yazmaya Giriş

Hadi pratik yapalım!

R'de Fonksiyon Yazmaya Giriş

Preparing Video For Download...