Custom Functions in R
In this lesson, you will learn how to create your own custom functions in R. Custom functions allow you to group logic into reusable blocks of code.
Instead of writing the same code again and again, you can write it once inside a function and use it whenever needed.
Why Do We Need Custom Functions?
As programs grow bigger, repeating the same steps becomes difficult to manage.
Custom functions help you:
- Reduce repeated code
- Improve readability
- Make programs easier to maintain
- Reuse logic across different tasks
Basic Structure of a Function
In R, functions are created using the function() keyword.
A function can accept inputs (arguments), perform operations, and return a result.
function_name <- function(arguments) {
# code to execute
return(result)
}
Creating a Simple Function
Let’s create a simple function that adds two numbers.
add_numbers <- function(a, b) {
result <- a + b
return(result)
}
This function takes two values and returns their sum.
Calling a Function
Once a function is defined, you can call it by using its name followed by values.
add_numbers(10, 20)
The function executes and returns the calculated result.
Functions Without Arguments
Some functions do not require any input values.
They simply perform a task when called.
show_message <- function() {
print("Welcome to Dataplexa R Course")
}
show_message()
Functions with Default Values
You can assign default values to function arguments.
If no value is provided, the default value is used automatically.
power <- function(x, y = 2) {
x ^ y
}
power(5)
power(5, 3)
This makes functions flexible and easy to use.
Returning Values from a Function
Functions usually return a value using the return() statement.
If return() is not used, R returns the last evaluated expression.
multiply <- function(a, b) {
a * b
}
multiply(4, 6)
Using Functions Inside Other Functions
Functions can be combined to build more complex logic.
This helps create clean and modular programs.
square <- function(x) {
x ^ 2
}
cube <- function(x) {
x * square(x)
}
cube(3)
📝 Practice Exercises
Exercise 1
Create a function that subtracts two numbers.
Exercise 2
Write a function that calculates the average of a numeric vector.
Exercise 3
Create a function with a default argument that greets a user.
Exercise 4
Write a function that checks whether a number is even or odd.
✅ Practice Answers
Answer 1
subtract <- function(a, b) {
a - b
}
subtract(10, 4)
Answer 2
average <- function(values) {
mean(values)
}
average(c(10, 20, 30))
Answer 3
greet <- function(name = "User") {
paste("Hello", name)
}
greet()
greet("Alex")
Answer 4
check_even_odd <- function(x) {
if (x %% 2 == 0) {
"Even"
} else {
"Odd"
}
}
check_even_odd(7)
What’s Next?
In the next lesson, you will learn how to work with packages and libraries in R.
This will help you extend R’s functionality for data analysis and visualization.