Creating functions R
A really useful way to organize your code is by creating functions. Functions allow you to encapsulate code that performs a specific task, making your scripts more modular and easier to read. You should always consider creating functions, whenever you find yourself repeating code or performing a specific task multiple times.
In R, you can create a function using the function
keyword. Here is a simple example of a function that adds two numbers:
This is a simple function that takes two arguments and returns their sum. In the function call function(a, b)
the arguments a
and b
are passed to the function. They will be used locally within the function. The return
statement specifies what the function will output when it is called. In this case, it returns the sum of a
and b
.
You can then call this function with different arguments, but the arguments must match the function’s parameters:
Here we called the function without specifying the variable names. The function uses the values in the same order as the parameters are defined. In R you can also call the function with named arguments:
Note, that you can reorder the arguments when using named parameters in the function call.
Functions can also have default argument values. For example:
In this case, if you call add_numbers(3)
, it will return 3
because b
defaults to 0
unless otherwise specified.
Creating functions is a powerful way to make your R code more efficient and easier to maintain.