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
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()
}
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() }
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
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))
ggplot(snake_river_visits, aes(n_visits)) +
geom_histogram(binwidth = 10)
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"
Introduction to Writing Functions in R