從函式回傳值

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
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()
}
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() }
R 函式撰寫入門

提早回傳的原因

  1. 你已經知道答案。
  2. 輸入屬於邊界情況。
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
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))


R 函式撰寫入門

許多圖會隱性回傳物件

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

Snake River 造訪次數的長條圖。分佈右偏,多數人在每年不到 5 次的左側區間;最大值超過每年 300 次。

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"

與前一張投影片相同的 Snake River 造訪次數長條圖。

R 函式撰寫入門

一起來練習吧!

R 函式撰寫入門

Preparing Video For Download...