R Functions Intro
A function is a named, reusable block of code that performs a specific task. Instead of writing the same calculation five times across your script, you write it once as a function and call it by name whenever you need it. Functions make your code shorter, easier to test, and simpler to maintain.
Function Anatomy
function_name <- function(parameter1, parameter2) {
# body: the code that runs
result <- parameter1 + parameter2
return(result) # send back the answer
}
Diagram:
Input → [parameter1, parameter2]
│
function body
│
Output ← return(result)
Your First Function
# Define the function
greet <- function(name) {
message <- paste("Hello,", name, "! Welcome to R.")
return(message)
}
# Call the function
greet("Priya")
# [1] "Hello, Priya ! Welcome to R."
greet("Arjun")
# [1] "Hello, Arjun ! Welcome to R."
Function With Multiple Parameters
rectangle_area <- function(length, width) {
area <- length * width
return(area)
}
rectangle_area(8, 5) # 40
rectangle_area(12, 3) # 36
Implicit Return
R automatically returns the value of the last evaluated expression. The explicit return() call is optional but recommended for clarity.
square <- function(x) {
x ^ 2 # last expression is returned automatically
}
square(7) # 49
Functions as Objects
In R, functions are objects — just like variables. You can assign them, pass them to other functions, and store them in lists.
# Function stored in a variable double <- function(x) x * 2 # Pass a function to another function apply_fn <- function(x, fn) fn(x) apply_fn(5, double) # 10
Checking if a Function Exists
is.function(mean) # TRUE is.function(sum) # TRUE is.function(42) # FALSE (not a function)
Viewing Function Source Code
# For user-defined functions, just type the name without () greet # prints the function code # For built-in functions body(mean) # body of the function formals(mean) # argument list
Practical Example: BMI Calculator Function
calculate_bmi <- function(weight_kg, height_m) {
bmi <- weight_kg / (height_m ^ 2)
bmi <- round(bmi, 1)
category <- if (bmi < 18.5) "Underweight" else
if (bmi < 25) "Normal" else
if (bmi < 30) "Overweight" else
"Obese"
return(list(bmi = bmi, category = category))
}
result <- calculate_bmi(70, 1.75)
cat("BMI:", result$bmi, "—", result$category, "\n")
Output:
BMI: 22.9 — Normal
Function Best Practices
- Give functions verb-based names:
calculate_tax(),clean_data(),plot_sales() - Each function should do one thing well
- Keep functions short — if a function exceeds 20-30 lines, consider splitting it
- Document what arguments the function expects and what it returns
Functions are the building blocks of organized R code. Every package you install is a collection of functions. Every analysis script benefits from pulling repeated logic into functions. The investment in learning to write good functions pays off every day you use R.
