We aren’t computer scientists and that’s okay!
We make lots of mistakes. Mistakes are funny. You can laugh with us.
Let’s go, Simba, Pumbaa, and Timon!
Almost everthing in R is done through functions.
Here are some commonly used functions that work with numbers.
abs(x) absolute value
sqrt(x) square root – x^(1/2), x**(1/2)
round(x, digits = n) round x to n decimal digits
log(x) natural logarithm (base e)
log10(x) common logarithm (base 10)
exp(x) exponentials e^x
mean(x, na.rm = FALSE) mean of x
median(x) median of x
sd(x) standard deviation of x
quantile(x, probs) quantiles of x with probability
range(x) smallest to largest values
max(x) maximum
min(x) minimum
sum(x) summation
One of the great strengths of R is user can write customized functions.
In general, if you find yourself doing a lot of cutting and pasting, that’s usually a good sign to write a function.
Functions are defined using the function() and are stored as R objects just like anything else.
# Basic structure of creating a function
function_name <- function(arguments) {
function body
}
# A simple example: convert Fahrenheit to Celsius
f_to_c <- function(temp_F) {
temp_C <- (temp_F - 32) * 5 / 9
#return(temp_C),
}
# In R, the return value of a function is always the very last expression that is evaluated
print(f_to_c(32))
airquality %>%
mutate(temp_c = f_to_c(Temp))
R functions arguments can be matched by position or by name.
Position matching just means that R assigns the first value to the first argument, the second value to second argument.
We must provide the argument values in the obtain_match() function if defualt values are not available
We can modify the function to avoid such error by providing default values for arguments
You can create and use functions inside your script.
#create a function to convert a month to season
obtain_season <- function(month){
case_when(month %in% c(12, 1, 2) ~ "winter",
month %in% c(3, 4, 5) ~ "spring",
month %in% c(6, 7, 8) ~ "summer",
month %in% c(9, 10, 11) ~ "fall")
}
obtain_season(7)
#apply the obtain_season() function
library(tidyverse)
airquality %>%
mutate(season = obtain_season(Month))
You can also save your functions in a different script and use them again and again.
# we created a obtain_season() function and saved it in the my_functions.R
source('./script/my_functions.R') #use source() to read R code
class(obtain_season)
airquality %>%
mutate(season = obtain_season(Month))
Exercise
Write a function using year, month and day to obtain weekday/weekend: obtain_weekend()
Apply the function on airquality dataset
Some built-in functions for numbers
Write functions