การคืนค่าจากฟังก์ชัน

Introduction to Writing Functions in R

Richie Cotton

Data Evangelist at DataCamp

ฟังก์ชันบวกเลขอย่างง่าย

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

ค่าเฉลี่ยเรขาคณิต อีกครั้ง

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

คืนค่า NaN พร้อมคำเตือน

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

เหตุผลที่ควรคืนค่าก่อนกำหนด

  1. ทราบคำตอบอยู่แล้ว
  2. อินพุตเป็น edge case
Introduction to Writing Functions in R

การซ่อนค่าที่คืนกลับ

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

การซ่อนค่าที่คืนกลับ

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

กราฟจำนวนมากคืนค่าแบบ invisible

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

ฮิสโทแกรมของการเยี่ยมชม Snake River การกระจายเบ้ขวา โดยส่วนใหญ่อยู่ในช่วงต่ำกว่า 5 ครั้งต่อปี และค่าสูงสุดอยู่ที่กว่า 300 ครั้งต่อปี

Introduction to Writing Functions in R

กราฟจำนวนมากคืนค่าแบบ invisible

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"

ฮิสโทแกรมเดิมของการเยี่ยมชม Snake River จากสไลด์ก่อนหน้า

Introduction to Writing Functions in R

มาฝึกกันเถอะ!

Introduction to Writing Functions in R

Preparing Video For Download...