Introduction to Writing Functions in R
Richie Cotton
Data Evangelist at DataCamp
calc_geometric_mean <- function(x, na.rm = FALSE) {
x %>%
log() %>%
mean(na.rm = na.rm) %>%
exp()
}
calc_geometric_mean(letters)
Error in log(.) : non-numeric argument to mathematical function
calc_geometric_mean <- function(x, na.rm = FALSE) {if(!is.numeric(x)) {stop("x is not of class 'numeric'; it has class '", class(x), "'.")}x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
Error in calc_geometric_mean(letters) :
x is not of class 'numeric'; it has class 'character'.

assert_is_numeric()assert_is_character()is_data.frame()is_two_sided_formula()is_tskernel()calc_geometric_mean <- function(x, na.rm = FALSE) {assert_is_numeric(x)x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
Error in calc_geometric_mean(letters) :
is_numeric : x is not of class 'numeric'; it has class 'character'.
calc_geometric_mean <- function(x, na.rm = FALSE) { assert_is_numeric(x)assert_all_are_positive(x)x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
calc_geometric_mean(c(1, -1))
Error in calc_geometric_mean(c(1, -1)) :
is_positive : x contains non-positive values.
There was 1 failure:
Position Value Cause
1 2 -1 too low
assert_is_numeric()assert_all_are_positive()is_numeric() (returns logical value)is_positive() (returns logical vector)is_non_positive()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.") }x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
calc_geometric_mean(c(1, -1))
Error in calc_geometric_mean(c(1, -1)) :
x contains non-positive values, so the geometric mean makes no sense.
use_first(c(1, 4, 9, 16))
[1] 1
Warning message:
Only the first value of c(1, 4, 9, 16) (= 1) will be used.
coerce_to(c(1, 4, 9, 16), "character")
[1] "1" "4" "9" "16"
Warning message:
Coercing c(1, 4, 9, 16) to class ‘character’.
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), target_class = "logical")x %>% log() %>% mean(na.rm = na.rm) %>% exp() }
calc_geometric_mean(1:5, na.rm = 1:5)
[1] 2.605171
Warning messages:
1: Only the first value of na.rm (= 1) will be used.
2: Coercing use_first(na.rm) to class ‘logical’.
Introduction to Writing Functions in R