input --> function does something --> output
Main benefit: Avoid repetition.
Another advantage: Self contained code such that any variable you create inside a function will not be exported into your global environment.
## Fahrenheit to Celsius (70 - 32) * 5/9
## [1] 21.11111
(65 - 32) * 5/9
## [1] 18.33333
(85 - 32) * 5/9
## [1] 29.44444
Let's convert this into a function:
fahr_to_celsius <- function(temp) { (temp - 32) * 5/9 }
Don't forget to re-evaluate your function, after modifying it.
A little better:
convert_fahr <- function(temp, to) { res <- (temp - 32) * 5/9 if (to == "kelvin") { res <- res + 273.15 } res }
With functions you can easily control the format of the input and avoid the chances for typos or other small mistakes.
convert_fahr <- function(temp, to = c("celsius", "kelvin")) { to <- tolower(to) to <- match.arg(to) res <- (temp - 32) * 5/9 if (to == "kelvin") { res <- res + 273.15 } res }
Let's refactor this function into something even better that will allow you to easily expend the convert_fahr
function to other units:
fahr_to_celsius <- function(temp) { (temp - 32) * 5/9 } celsius_to_kelvin <- function(temp) { temp + 273.15 } convert_fahr <- function(temp, to = c("celsius", "kelvin")) { to <- tolower(to) to <- match.arg(to) res <- fahr_to_celsius(temp) if (to == "kelvin") { res <- celsius_to_kelvin(res) } res }
Your intentions are clear, everything is self contained, you can easily debug, test and document each of the steps involved.
Write a function that converts pounds in kilograms (divides by 2.2).
Stretch goal: and in grams.