Menu
Coddy logo textTech

Declaring a Function

Part of the Fundamentals section of Coddy's R journey — lesson 46 of 78.

So far, you've been writing code that runs from top to bottom. But what if you need to perform the same task multiple times in different places? Instead of copying and pasting code, you can create a function - a reusable block of code that you can call whenever you need it.

In R, you declare a function using the function keyword:

greet <- function() {
  print("Hello!")
}

greet()

Output:

[1] "Hello!"

Let's break this down. We assign a function to the name greet using the assignment operator.

The parentheses () after function are where parameters would go (we'll cover those next). The curly braces {} contain the code that runs when the function is called.

To use the function, you simply write its name followed by parentheses: greet(). This is called calling or invoking the function.

You can call it as many times as you want:

greet()
greet()
greet()

Output:

[1] "Hello!"
[1] "Hello!"
[1] "Hello!"

Functions help you organize your code, avoid repetition, and make your programs easier to read and maintain.

challenge icon

Challenge

Easy

Create a function called say_goodbye that takes no arguments. When called, the function should print the message "Goodbye, see you soon!" using print().

After declaring the function, call it twice to display the message two times.

The output should be:

[1] "Goodbye, see you soon!"
[1] "Goodbye, see you soon!"

Cheat sheet

A function is a reusable block of code that you can call whenever needed.

To declare a function in R, use the function keyword and assign it to a name:

greet <- function() {
  print("Hello!")
}

The parentheses () after function are for parameters. The curly braces {} contain the code that runs when the function is called.

To call (invoke) a function, write its name followed by parentheses:

greet()

You can call a function multiple times:

greet()
greet()
greet()

Try it yourself

# TODO: Write your code below
# 1. Create a function called say_goodbye that prints "Goodbye, see you soon!"
# 2. Call the function twice
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals