mean(1:5)[1] 3
Functions are reusable blocks of code designed to perform a specific task.
Writing functions improves clarity, efficiency, and reproducibility.
stopifnot()R provides many built-in functions for analysis, including:
mean(1:5)[1] 3
Handling missing values:
To use functions from packages:
You create a function using function().
f <- function(arg1, arg2, arg3, ...){
# code
}squareroot <- function(a){
a^0.5
}
squareroot(49)[1] 7
Addtwo <- function(a, b){
a + b
}
Addtwo(1, 2)[1] 3
R automatically returns the last evaluated expression, but return() makes it explicit.
F2C <- function(temp) {
c <- (temp - 32) * (5 / 9)
return(c)
}
F2C(100)[1] 37.77778
Use a list to return multiple outputs.
You can assign default values to arguments.
power <- function(x, exponent = 2){
x^exponent
}
power(3) # uses default exponent = 2[1] 9
power(3, 3) # overrides default[1] 27
Default arguments make functions more flexible.
Nested functions combine multiple operations inside one expression.
Example using mtcars:
Goal: Compute the mean mpg for cars with 4 cylinders.
Step-by-step approach:
Nested version:
mean(mtcars$mpg[mtcars$cyl == 4])[1] 26.66364
You can also define functions inside functions:
outer_function <- function(x){
inner_function <- function(y){
y^2
}
inner_function(x) + 1
}
outer_function(3)[1] 10
Functions should check inputs to avoid incorrect results.
stopifnot()
If the condition fails, R stops execution.
stop()
safe_divide <- function(a, b){
if(b == 0){
stop("Division by zero is not allowed.")
}
a / b
}warning()
check_positive <- function(x){
if(x < 0){
warning("Negative value detected.")
}
x
}function()stopifnot() or stop()