What are the arguments and parameters in R?

Overview

An argument in R is the information passed into a function. In simpler terms, an argument is a value that is sent to a function when it is called.

The parameter is the value enclosed in the parentheses whenever a function is created.

Function in R

A function, on the other hand, is a block of code that will run only when it is called. To create a function, we simply use the function() keyword.

Creating and calling a function

To create a function in R, we use the function() keyword. To call a function in R, we simply use the name of the function we created alongside a parenthesis. For example, we will type my_function() if we want to call a function my_function that we have created.

Code example

The code below will illustrate how to create and call a function in R.

# creating a function # create a function with the name my_function
my_function <- function() {
print("Hello World!")
}
# calling the function we created in order to execute its command
my_function()

As can be seen from the output of the code above, the function is executed because we call the function.

Passing parameters and arguments to a function

We can pass parameters as well as arguments to a function. We can also add many arguments to a function. To separate each argument in a function, we use commas.

Code Example

The code below will illustrate how to create a function, how to pass parameters and arguments to a function, and how to return the arguments we passed to a function.

# creating a function and passing a parameter functionName
myFunction <- function(functionName) {
paste(functionName, "World!")
}
# passing the arguments
myFunction("Hello")
myFunction("Hi")
myFunction("Holla")

Explanation

  • Line 2: We create a function myFunction and pass an argument functionName to it.
  • Line 3: We pass a command to the function to execute whenever the function is called.
  • Line 6-8: We call the function and pass arguments to it.

It is worth noting that an argument is different from a parameter, such that an argument is the variable listed inside the parenthesis whenever a function is called. The arguments in the code above includes Hello, Hi, and Holla. On the other hand, a parameter is a value listed inside the parenthesis whenever we create a function. The parameter in the code above is functionName.

Free Resources