Menu
Coddy logo textTech

Function Arguments

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

Functions become much more powerful when they can accept input. Arguments (also called parameters) let you pass values into a function, making it flexible and reusable for different situations.

To add arguments, place them inside the parentheses when defining the function:

greet <- function(name) {
  print(paste("Hello,", name))
}

greet("Alice")
greet("Bob")

Output:

[1] "Hello, Alice"
[1] "Hello, Bob"

The function now works with any name you provide. When you call greet("Alice"), the value "Alice" is assigned to the name parameter inside the function.

You can define multiple arguments by separating them with commas:

add <- function(a, b) {
  print(a + b)
}

add(5, 3)
add(10, 20)

Output:

[1] 8
[1] 30

When calling a function with multiple arguments, the values are matched to parameters in order. The first value goes to the first parameter, the second value to the second parameter, and so on.

challenge icon

Challenge

Easy

Create a function called calculate_area that takes two arguments: length and width. The function should print the area (length multiplied by width) using print().

Read two numbers from input, convert them to numeric values, and call your function with these values.

For example, if the inputs are 5 and 3, the output should be:

[1] 15

If the inputs are 7 and 4, the output should be:

[1] 28

Cheat sheet

Functions can accept arguments (parameters) to make them flexible and reusable. Arguments are placed inside the parentheses when defining the function:

greet <- function(name) {
  print(paste("Hello,", name))
}

greet("Alice")  # [1] "Hello, Alice"

When you call the function, the value you pass is assigned to the parameter inside the function.

You can define multiple arguments by separating them with commas:

add <- function(a, b) {
  print(a + b)
}

add(5, 3)  # [1] 8

When calling a function with multiple arguments, values are matched to parameters in order.

Try it yourself

# Read input
con <- file("stdin", "r")
length <- as.numeric(suppressWarnings(readLines(con, n = 1)))
width <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)

# TODO: Create a function called calculate_area that takes length and width
# and prints the area (length * width)


# Call your function with the input values
quiz iconTest yourself

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

All lessons in Fundamentals