Create a function in R with function()

There is a lot of function in R, but did you know that you can create yours too?

To create your functions,  you have to assign a function to an object with function(). You have to assign some parameters to function(), that we can predefine or not. If a parameter isn't set, it will be required. If it is predefined, you can edit it at the launch.

There is an example:

myFunction <- function(variable1, variable2 = TRUE) {
if (variable2 == TRUE)
{print("The variable 2 isn't modified")} else {
print("The variable 2 is modified")}

The R function that we created use 2 variables. The first isn't predefined, so you have to write a value. The second is predefined, so you can avoid mentioning a value at the launch of the function or edit it.

Create its own function can be very useful when an action will be repeated. The data processing will be faster and more effective.

The action that will be dedicated to be repeated will be formatted for a unique format, that can avoid processing mistakes.

Launch a custom function in R

To launch a function that we created, you have to call the object like any other function, the launch is the same. There is an example.

myFunction("The value of my variable 1")

This will return the following response.

The value of my variable 1
The variable 2 isn't modified

Use the function return() on a custom function

The objects created on a function aren't available on the global environment. To return a value, you have to use the function return(). There is an example.

myFunction <- function(variable1, variable2) {
myResult <- variable1 + variable2

If we launch the function like this…

myFunction(4, 8)

… we obtain the following response.


Now, you can create more advanced function and perhaps create your own R library.