从函数返回值

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