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.
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.
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.
The code below will illustrate how to create and call a function in R.
# creating a function # create a function with the name my_functionmy_function <- function() {print("Hello World!")}# calling the function we created in order to execute its commandmy_function()
As can be seen from the output of the code above, the function is executed because we call the 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.
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 functionNamemyFunction <- function(functionName) {paste(functionName, "World!")}# passing the argumentsmyFunction("Hello")myFunction("Hi")myFunction("Holla")
myFunction
and pass an argument functionName
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
, andHolla
. On the other hand, a parameter is a value listed inside the parenthesis whenever we create a function. The parameter in the code above isfunctionName
.