source("../bin/chunk-options.R") knitr_fig_path("02-func-R-")
If we only had one data set to analyze, it would probably be faster to load the file into a spreadsheet and use that to plot some simple statistics. But we have twelve files to check, and may have more in the future. In this lesson, we'll learn how to write a function so that we can repeat several operations with a single command.
Let's start by defining a function fahrenheit_to_celsius
that converts temperatures from Fahrenheit to Celsius:
fahrenheit_to_celsius <- function(temp_F) { temp_C <- (temp_F - 32) * 5 / 9 return(temp_C) }
We define fahrenheit_to_celsius
by assigning it to the output of function
.
The list of argument names are contained within parentheses.
Next, the body of the function--the statements that are executed when it runs--is contained within curly braces ({}
).
The statements in the body are indented by two spaces, which makes the code easier to read but does not affect how the code operates.
When we call the function, the values we pass to it are assigned to those variables so that we can use them inside the function. Inside the function, we use a return statement to send a result back to whoever asked for it.
```{callout "30:1-36:12"}
Let's try running our function. Calling our own function is no different from calling any other function: ```r # freezing point of water fahrenheit_to_celsius(32) # boiling point of water fahrenheit_to_celsius(212)
We've successfully called the function that we defined, and we have access to the value that we returned.
Now that we've seen how to turn Fahrenheit into Celsius, it's easy to turn Celsius into Kelvin:
celsius_to_kelvin <- function(temp_C) { temp_K <- temp_C + 273.15 return(temp_K) } # freezing point of water in Kelvin celsius_to_kelvin(0)
What about converting Fahrenheit to Kelvin? We could write out the formula, but we don't need to. Instead, we can compose the two functions we have already created:
fahrenheit_to_kelvin <- function(temp_F) { temp_C <- fahrenheit_to_celsius(temp_F) temp_K <- celsius_to_kelvin(temp_C) return(temp_K) } # freezing point of water in Kelvin fahrenheit_to_kelvin(32.0)
This is our first taste of how larger programs are built: we define basic operations, then combine them in ever-larger chunks to get the effect we want. Real-life functions will usually be larger than the ones shown here--typically half a dozen to a few dozen lines--but they shouldn't ever be much longer than that, or the next person who reads it won't be able to understand what's going on.
````{callout "83:1-93:5"}
fahrenheit_to_celsius
assigned to temp_C
, whichcelsius_to_kelvin
to get the final result. It is also possiblecelsius_to_kelvin(fahrenheit_to_celsius(32.0))
````{challenge "96:1-151:14"} #' ## Create a Function #' #' In the last lesson, we learned to **c**ombine elements into a vector using the `c` function, #' e.g. `x <- c("A", "B", "C")` creates a vector `x` with three elements. #' Furthermore, we can extend that vector again using `c`, e.g. `y <- c(x, "D")` creates a vector `y` with four elements. #' Write a function called `highlight` that takes two vectors as arguments, called #' `content` and `wrapper`, and returns a new vector that has the wrapper vector #' at the beginning and end of the content: #' #' ```r highlight <- function(content, wrapper) { answer <- c(wrapper, content, wrapper) return(answer) } best_practice <- c("Write", "programs", "for", "people", "not", "computers") asterisk <- "***" # R interprets a variable with a single value as a vector # with one element. highlight(best_practice, asterisk) #' ``` #' #' @solution Solution #' #' ``` highlight <- function(content, wrapper) { answer <- c(wrapper, content, wrapper) return(answer) } #' ``` #' #' @challenge #' #' #' ```r edges <- function(v) { first <- v[1] last <- v[length(v)] answer <- c(first, last) return(answer) } dry_principle <- c("Don't", "repeat", "yourself", "or", "others") edges(dry_principle) #' ``` #' #' @solution Solution #' #' ``` edges <- function(v) { first <- v[1] last <- v[length(v)] answer <- c(first, last) return(answer) } #' ```
```{callout "153:1-160:12"}
````{challenge "162:1-192:14"} #' ## Named Variables and the Scope of Variables #' #' Functions can accept arguments explicitly assigned to a variable name in #' the function call `functionName(variable = value)`, as well as arguments by #' order: #' #' ```r input_1 <- 20 mySum <- function(input_1, input_2 = 10) { output <- input_1 + input_2 return(output) } #' ``` #' #' 1. Given the above code was run, which value does `mySum(input_1 = 1, 3)` produce? #' 1. 4 #' 2. 11 #' 3. 23 #' 4. 30 #' 2. If `mySum(3)` returns 13, why does `mySum(input_2 = 3)` return an error? #' #' @solution Solution #' #' 1. The solution is `1.`. #' #' 2. Read the error message: `argument "input_1" is missing, with no default` #' means that no value for `input_1` is provided in the function call, #' and neither in the function's defintion. Thus, the addition in the #' function body can not be completed. ```` ### Testing and Documenting Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To see how to do this, let's write a function to center a dataset around a particular midpoint: ```r center <- function(data, midpoint) { new_data <- (data - mean(data)) + midpoint return(new_data) }
We could test this on our actual data, but since we don't know what the values ought to be, it will be hard to tell if the result was correct. Instead, let's create a vector of 0s and then center that around 3. This will make it simple to see if our function is working as expected:
z <- c(0, 0, 0, 0) z center(z, 3)
That looks right, so let's try center on our real data. We'll center the inflammation data from day 4 around 0:
dat <- read.csv(file = "data/inflammation-01.csv", header = FALSE) centered <- center(dat[, 4], 0) head(centered)
It's hard to tell from the default output whether the result is correct, but there are a few simple tests that will reassure us:
# original min min(dat[, 4]) # original mean mean(dat[, 4]) # original max max(dat[, 4]) # centered min min(centered) # centered mean mean(centered) # centered max max(centered)
That seems almost right: the original mean was about r round(mean(dat[, 4]), 2)
, so the lower bound from zero is now about r -round(mean(dat[, 4]), 2)
.
The mean of the centered data is r mean(centered)
.
We can even go further and check that the standard deviation hasn't changed:
# original standard deviation sd(dat[, 4]) # centered standard deviation sd(centered)
Those values look the same, but we probably wouldn't notice if they were different in the sixth decimal place. Let's do this instead:
# difference in standard deviations before and after sd(dat[, 4]) - sd(centered)
Sometimes, a very small difference can be detected due to rounding at very low decimal places.
R has a useful function for comparing two objects allowing for rounding errors, all.equal
:
all.equal(sd(dat[, 4]), sd(centered))
It's still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis. We have one more task first, though: we should write some documentation for our function to remind ourselves later what it's for and how to use it.
A common way to put documentation in software is to add comments like this:
center <- function(data, midpoint) { # return a new vector containing the original data centered around the # midpoint. # Example: center(c(1, 2, 3), 0) => c(-1, 0, 1) new_data <- (data - mean(data)) + midpoint return(new_data) }
```{callout "283:1-292:12"}
.Rd
using a?read.csv
..Rd
files.```r analyze <- function(filename) { # Plots the average, min, and max inflammation over time. # Input is character string of a csv file. dat <- read.csv(file = filename, header = FALSE) avg_day_inflammation <- apply(dat, 2, mean) plot(avg_day_inflammation) max_day_inflammation <- apply(dat, 2, max) plot(max_day_inflammation) min_day_inflammation <- apply(dat, 2, min) plot(min_day_inflammation) }
rescale <- function(v) { # Rescales a vector, v, to lie in the range 0 to 1. L <- min(v) H <- max(v) result <- (v - L) / (H - L) return(result) }
````{challenge 321:1-345:14"}
analyze
that takes a filename as an argumentanalyze("data/inflammation-01.csv")
should produce the graphs already shown,analyze("data/inflammation-02.csv")
should produce corresponding graphs for the second data set.analyze <- function(filename) { # Plots the average, min, and max inflammation over time. # Input is character string of a csv file. dat <- read.csv(file = filename, header = FALSE) avg_day_inflammation <- apply(dat, 2, mean) plot(avg_day_inflammation) max_day_inflammation <- apply(dat, 2, max) plot(max_day_inflammation) min_day_inflammation <- apply(dat, 2, min) plot(min_day_inflammation) }
````{challenge "347:1-367:14"} #' ## Rescaling #' #' Write a function `rescale` that takes a vector as input and returns a corresponding vector of values scaled to lie in the range 0 to 1. #' (If `L` and `H` are the lowest and highest values in the original vector, then the replacement for a value `v` should be `(v-L) / (H-L)`.) #' Be sure to document your function with comments. #' #' Test that your `rescale` function is working properly using `min`, `max`, and `plot`. #' #' @solution Solution #' #' ``` rescale <- function(v) { # Rescales a vector, v, to lie in the range 0 to 1. L <- min(v) H <- max(v) result <- (v - L) / (H - L) return(result) } #' ```
[01]: {{ page.root }}/01-starting-with-data/
answer <- rescale(dat[, 4]) min(answer) max(answer) plot(answer) plot(dat[, 4], answer) # This hasn't been introduced yet, but it may be # useful to show when explaining the answer.
We have passed arguments to functions in two ways: directly, as in dim(dat)
, and by name, as in read.csv(file = "data/inflammation-01.csv", header = FALSE)
.
In fact, we can pass the arguments to read.csv
without naming them:
dat <- read.csv("data/inflammation-01.csv", FALSE)
However, the position of the arguments matters if they are not named.
dat <- read.csv(header = FALSE, file = "data/inflammation-01.csv") dat <- read.csv(FALSE, "data/inflammation-01.csv")
To understand what's going on, and make our own functions easier to use, let's re-define our center
function like this:
center <- function(data, midpoint = 0) { # return a new vector containing the original data centered around the # midpoint (0 by default). # Example: center(c(1, 2, 3), 0) => c(-1, 0, 1) new_data <- (data - mean(data)) + midpoint return(new_data) }
The key change is that the second argument is now written midpoint = 0
instead of just midpoint
.
If we call the function with two arguments, it works as it did before:
test_data <- c(0, 0, 0, 0) center(test_data, 3)
But we can also now call center()
with just one argument, in which case midpoint
is automatically assigned the default value of 0
:
more_data <- 5 + test_data more_data center(more_data)
This is handy: if we usually want a function to work one way, but occasionally need it to do something else, we can allow people to pass an argument when they need to but provide a default to make the normal case easier.
The example below shows how R matches values to arguments
display <- function(a = 1, b = 2, c = 3) { result <- c(a, b, c) names(result) <- c("a", "b", "c") # This names each element of the vector return(result) } # no arguments display() # one argument display(55) # two arguments display(55, 66) # three arguments display(55, 66, 77)
As this example shows, arguments are matched from left to right, and any that haven't been given a value explicitly get their default value. We can override this behavior by naming the value as we pass it in:
# only setting the value of c display(c = 77)
```{callout "453:1-464:12"}
With that in hand, let's look at the help for `read.csv()`: ```r ?read.csv
There's a lot of information there, but the most important part is the first couple of lines:
read.csv(file, header = TRUE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "", ... )
This tells us that read.csv()
has one argument, file
, that doesn't have a default value, and six others that do.
Now we understand why the following gives an error:
dat <- read.csv(FALSE, "data/inflammation-01.csv")
It fails because FALSE
is assigned to file
and the filename is assigned to the argument header
.
````{challenge "488:1-507:14"}
rescale
function so that it scales a vector to lie between 0 and 1 by default, but will allow the caller to specify lower and upper bounds if they want.rescale <- function(v, lower = 0, upper = 1) { # Rescales a vector, v, to lie in the range lower to upper. L <- min(v) H <- max(v) result <- (v - L) / (H - L) * (upper - lower) + lower return(result) }
````
rescale <- function(v, lower = 0, upper = 1) { # Rescales a vector, v, to lie in the range lower to upper. L <- min(v) H <- max(v) result <- (v - L) / (H - L) * (upper - lower) + lower return(result) } answer <- rescale(dat[, 4], lower = 2, upper = 5) min(answer) max(answer) answer <- rescale(dat[, 4], lower = -5, upper = -2) min(answer) max(answer)
{% include links.md %}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.