We write functions to make our code easier to read and to reduce the chance of errors. Copying and pasting the same code several times means we have to change the input in several places, and it is easy to forget one. A function lets us change the input only once.
We do not need any extra package: functions are built with base R. The base R cheat sheet (Programming section) shows the basic structure:
function_name <- function(variable) {
# do something (the body of the function)
return(new_variable)
}
You should consider writing a function whenever you have copied and
pasted a block of code more than twice. Here is the example from the
book. rnorm(10) creates ten random values from a normal
distribution (default mean 0 and standard deviation 1).
set.seed() makes the random values reproducible, so we get
the same numbers every time we run the code.
set.seed(1234) # for reproducible work
df <- tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
df
## # A tibble: 10 × 4
## a b c d
## <dbl> <dbl> <dbl> <dbl>
## 1 -1.21 -0.477 0.134 1.10
## 2 0.277 -0.998 -0.491 -0.476
## 3 1.08 -0.776 -0.441 -0.709
## 4 -2.35 0.0645 0.460 -0.501
## 5 0.429 0.959 -0.694 -1.63
## 6 0.506 -0.110 -1.45 -1.17
## 7 -0.575 -0.511 0.575 -2.18
## 8 -0.547 -0.911 -1.02 -1.34
## 9 -0.564 -0.837 -0.0151 -0.294
## 10 -0.890 2.42 -0.936 -0.466
This expression rescales column a so its values run from
0 to 1: subtract the minimum, then divide by the range (maximum minus
minimum). df$a extracts column a as a numeric
vector.
df$a
## [1] -1.2070657 0.2774292 1.0844412 -2.3456977 0.4291247 0.5060559
## [7] -0.5747400 -0.5466319 -0.5644520 -0.8900378
min(df$a, na.rm = TRUE)
## [1] -2.345698
max(df$a, na.rm = TRUE)
## [1] 1.084441
max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE)
## [1] 3.430139
Doing this for all four columns by copy and paste means the column name appears five times in each line. It is tedious and easy to get wrong.
df_copy <- df # work on a copy so we can compare with the function version later
df_copy$a <- (df_copy$a - min(df_copy$a, na.rm = TRUE)) /
(max(df_copy$a, na.rm = TRUE) - min(df_copy$a, na.rm = TRUE))
df_copy$b <- (df_copy$b - min(df_copy$b, na.rm = TRUE)) /
(max(df_copy$b, na.rm = TRUE) - min(df_copy$b, na.rm = TRUE))
df_copy$c <- (df_copy$c - min(df_copy$c, na.rm = TRUE)) /
(max(df_copy$c, na.rm = TRUE) - min(df_copy$c, na.rm = TRUE))
df_copy$d <- (df_copy$d - min(df_copy$d, na.rm = TRUE)) /
(max(df_copy$d, na.rm = TRUE) - min(df_copy$d, na.rm = TRUE))
df_copy
## # A tibble: 10 × 4
## a b c d
## <dbl> <dbl> <dbl> <dbl>
## 1 0.332 0.153 0.782 1
## 2 0.765 0 0.473 0.519
## 3 1 0.0651 0.498 0.448
## 4 0 0.311 0.943 0.511
## 5 0.809 0.573 0.373 0.168
## 6 0.831 0.260 0 0.308
## 7 0.516 0.143 1 0
## 8 0.524 0.0255 0.210 0.256
## 9 0.519 0.0472 0.708 0.575
## 10 0.424 1 0.253 0.522
A function needs a name, the function() keyword with the
input variable(s) inside the parentheses, and a body inside curly
brackets. Ask: what changes each time I copy and paste? That is the
input. What stays the same? That is the body.
First, a simple example, square():
square <- function(variable) {
squared_value <- variable * variable
return(squared_value)
}
square(3)
## [1] 9
Now the rescaling function. The only thing that changes is the
vector, so x is the input.
rescale <- function(x) {
x <- (x - min(x, na.rm = TRUE)) /
(max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
return(x)
}
Using the function, we only change the input once per column:
df$a <- rescale(df$a)
df$b <- rescale(df$b)
df$c <- rescale(df$c)
df$d <- rescale(df$d)
df
## # A tibble: 10 × 4
## a b c d
## <dbl> <dbl> <dbl> <dbl>
## 1 0.332 0.153 0.782 1
## 2 0.765 0 0.473 0.519
## 3 1 0.0651 0.498 0.448
## 4 0 0.311 0.943 0.511
## 5 0.809 0.573 0.373 0.168
## 6 0.831 0.260 0 0.308
## 7 0.516 0.143 1 0
## 8 0.524 0.0255 0.210 0.256
## 9 0.519 0.0472 0.708 0.575
## 10 0.424 1 0.253 0.522
The values match the copy-and-paste version, but the code is much easier to read and less prone to errors.
all.equal(df, df_copy)
## [1] TRUE
Functions are not just for computers. They should be easy for people to read too. Key points from this section:
str_detect(),
str_extract(), str_replace()), not a common
suffix.#)
to explain the why of your code.# Not so good: the name is too short to tell us what the function does
f1 <- function(x) {
(x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
}
# Better: a verb that says what the function does
rescale_zero_one <- function(x) {
# Rescale so the minimum is 0 and the maximum is 1
(x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
}
rescale_zero_one(c(1, 5, 10))
## [1] 0.0000000 0.4444444 1.0000000
An if statement controls the flow of a function. It is
often used to check the type or format of the input and to give a
message, a warning, or stop the function. The condition must evaluate to
a single TRUE or FALSE. A condition with
length greater than one gives an error in current versions of R (older
versions gave a warning and used only the first element).
if (c(TRUE, FALSE)) {
"this condition has length greater than one"
}
## Error in `if (c(TRUE, FALSE)) ...`:
## ! the condition has length > 1
Use || and && (not |
and &) to combine logical conditions inside
if.
We start with one condition:
detect_sign <- function(x) {
if (x > 0) {
message("value is positive")
print(x)
}
}
detect_sign(3)
## value is positive
## [1] 3
detect_sign(0) # does nothing
Add else if for zero. A message() prints
before the value, a warning() prints after it:
detect_sign <- function(x) {
if (x > 0) {
message("value is positive")
print(x)
} else if (x == 0) {
warning("value is not positive, but it can be accepted")
print(x)
}
}
detect_sign(3)
## value is positive
## [1] 3
detect_sign(0)
## Warning in detect_sign(0): value is not positive, but it can be accepted
## [1] 0
Add else with stop() for negative values.
stop() ends the function, so the value is never
printed:
detect_sign <- function(x) {
if (x > 0) {
message("value is positive")
print(x)
} else if (x == 0) {
warning("value is not positive, but it can be accepted")
print(x)
} else {
stop("value is negative, the function must stop")
print(x)
}
}
detect_sign(3)
## value is positive
## [1] 3
detect_sign(0)
## Warning in detect_sign(0): value is not positive, but it can be accepted
## [1] 0
detect_sign(-1)
## Error in `detect_sign()`:
## ! value is negative, the function must stop
if and function are almost always followed
by curly brackets { }. The only exception is a very short
function that fits on one line, where the brackets can be dropped.
The arguments of a function usually fall into two sets: data (what to compute on) and details (arguments that control how the computation is done). The data is almost always the first argument.
mean() has x (the data) and
trim and na.rm (details).
?mean
x <- c(1:10, 100, NA) # one outlier (100) and one missing value (NA)
x
## [1] 1 2 3 4 5 6 7 8 9 10 100 NA
mean(x) # NA, because na.rm defaults to FALSE
## [1] NA
mean(x, na.rm = TRUE) # skewed by the outlier
## [1] 14.09091
mean(x, na.rm = TRUE, trim = 0.1) # trims 10% from each end, dropping the outlier
## [1] 6
...)We can write our own version of mean() that removes
NA by default. The ... passes any other
arguments (such as trim) on to the function inside.
mean_remove <- function(x, na.rm = TRUE, ...) {
average <- mean(x, na.rm = na.rm, ...)
return(average)
}
mean_remove(x) # uses the default na.rm = TRUE (includes the outlier)
## [1] 14.09091
mean_remove(x, na.rm = FALSE) # NA, because we told R not to remove NA
## [1] NA
mean_remove(x, trim = 0.1) # trim is passed through ... to mean()
## [1] 6
Some functions take a data frame as input, and some take a vector (a column) as input.
group_by() and summarize() (and
mutate()) take a data frame as the first argument
(.data):
gss_cat %>%
group_by(relig) %>%
summarize(
age = mean(age, na.rm = TRUE),
tvhours = mean(tvhours, na.rm = TRUE),
n = n()
)
## # A tibble: 15 × 4
## relig age tvhours n
## <fct> <dbl> <dbl> <int>
## 1 No answer 49.5 2.72 93
## 2 Don't know 35.9 4.62 15
## 3 Inter-nondenominational 40.0 2.87 109
## 4 Native american 38.9 3.46 23
## 5 Christian 40.1 2.79 689
## 6 Orthodox-christian 50.4 2.42 95
## 7 Moslem/islam 37.6 2.44 104
## 8 Other eastern 45.9 1.67 32
## 9 Hinduism 37.7 1.89 71
## 10 Buddhism 44.7 2.38 147
## 11 Other 41.0 2.73 224
## 12 None 41.2 2.71 3523
## 13 Jewish 52.4 2.52 388
## 14 Catholic 46.9 2.96 5124
## 15 Protestant 49.9 3.15 10846
mean() and median(), used inside
summarize(), take a vector: here the age and
tvhours columns:
mean(gss_cat$tvhours, na.rm = TRUE)
## [1] 2.980771