đ Introduction
A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you can define a function once and call it whenever needed. Functions improve code organization, reduce repetition, and make programs easier to understand and maintain.
Information
đ¯ Why Use Functions?
- Reduce code duplication.
- Improve program readability.
- Organize code into reusable modules.
- Simplify debugging and maintenance.
- Encourage code reusability.
đ Types of Functions in R
đš Built-in Functions
Built-in functions are predefined functions provided by R for performing common tasks.
Using Built-in Functions
numbers <- c(10, 20, 30, 40)
print(sum(numbers))
print(mean(numbers))
print(max(numbers))
print(min(numbers))
print(length(numbers))Output
Console Output
[1] 100
[1] 25
[1] 40
[1] 10
[1] 4đ Creating a User-Defined Function
Use the function() keyword to define your own function.
Syntax of a Function
function_name <- function(parameters) {
# Function body
return(value)
}Creating a Simple Function
greet <- function() {
print("Welcome to R Programming!")
}
greet()Output
Console Output
[1] "Welcome to R Programming!"đĨ Function Parameters
Parameters allow values to be passed into a function, making it more flexible and reusable.
Function with Parameters
greet <- function(name) {
print(paste("Hello", name))
}
greet("Alice")
greet("Bob")Output
Console Output
[1] "Hello Alice"
[1] "Hello Bob"đ¤ Returning Values
The return() function sends a value back to the function call. If return() is omitted, R automatically returns the value of the last evaluated expression.
Returning a Value
square <- function(number) {
return(number^2)
}
result <- square(6)
print(result)Output
Console Output
[1] 36đĸ Function with Multiple Parameters
Addition Function
add <- function(a, b) {
return(a + b)
}
print(add(10, 20))
print(add(15, 35))Output
Console Output
[1] 30
[1] 50âī¸ Default Parameter Values
Parameters can have default values, making them optional during function calls.
Default Parameters
greet <- function(name = "Guest") {
print(paste("Welcome", name))
}
greet()
greet("Sophia")Output
Console Output
[1] "Welcome Guest"
[1] "Welcome Sophia"đ Anonymous Functions
Anonymous functions are functions without a name. They are often used with functions such as lapply(), sapply(), and apply().
Anonymous Function
numbers <- c(1, 2, 3, 4)
result <- sapply(numbers, function(x) x^2)
print(result)Output
Console Output
[1] 1 4 9 16đ Nested Function Calls
Functions can call other functions to perform complex tasks.
Nested Functions
square <- function(x) {
x^2
}
cube_of_square <- function(x) {
square(x)^3
}
print(cube_of_square(2))Output
Console Output
[1] 64đ Variable Scope
Variables created inside a function are local variables and exist only within that function. Variables created outside a function are global variables.
Local and Global Variables
message <- "Global Variable"
showMessage <- function() {
message <- "Local Variable"
print(message)
}
showMessage()
print(message)Output
Console Output
[1] "Local Variable"
[1] "Global Variable"đ§Ž Real-World Example
The following function calculates the simple interest based on principal, rate, and time.
Simple Interest Calculator
simpleInterest <- function(principal, rate, time) {
interest <- (principal * rate * time) / 100
return(interest)
}
result <- simpleInterest(10000, 8, 2)
print(result)Output
Console Output
[1] 1600đ Function Execution Flow
đ Built-in vs User-Defined Functions
| Feature | Built-in Function | User-Defined Function |
|---|---|---|
| Created By | R Developers | Programmer |
| Availability | Already available | Must be created before use |
| Purpose | General tasks | Custom tasks |
| Examples | sum(), mean() | add(), simpleInterest() |
â ī¸ Common Mistakes
| Mistake | Explanation | Solution |
|---|---|---|
| Calling a function before defining it | The function does not exist yet. | Define the function before calling it. |
| Passing the wrong number of arguments | Results in an error or unexpected behavior. | Match the function parameters correctly. |
| Ignoring variable scope | Local variables are inaccessible outside the function. | Understand the difference between local and global variables. |
| Writing overly complex functions | Makes code difficult to maintain. | Keep functions short and focused on one task. |
đĄ Best Practices
- Give functions meaningful and descriptive names.
- Write functions that perform one specific task.
- Use parameters instead of hard-coded values.
- Include comments for complex logic.
- Reuse functions whenever possible instead of duplicating code.
Best Practice
đ Summary
Functions are reusable blocks of code that perform specific tasks in R. You learned how to use built-in functions, create user-defined functions, pass parameters, return values, define default arguments, use anonymous functions, understand variable scope, and build modular programs. Mastering functions is an essential step toward writing organized, efficient, and reusable R code for both simple scripts and large applications.