Monday, April 24, 2023

R Tutorial Playlist - Functions

Functions are basically pieces of code that you can call from your script repeatedly. But those pieces of code can accept different values in the form of arguments. This is how one simple function definition would look like: 

a <- function('list of arguments'){

    'statement to be executed'

}

If you want to provide known number of arguments to the function, do it in this way:

function(a, b, d, e)

In this case, all of arguments provided are mandatory to this function call.

If you want to provide optional arguments, here is the way

function(firs="some value", second= 13, third= FALSE)

Arguments where you use = to assign value, are not mandatory. You can declare as many you want during function declaration, but during function call, you don't have to provide a single one.

If you want to provide unknown number of arguments to the function you can do it in this way

function(...) 

Than, in order to access those arguments, you need statement 

args <-list(...)

where args is variable of type list that holds all of those arguments you have provided.

And finally, you can combine mandatory arguments, unknown number of arguments and optional arguments in the same function call. Definition for that function would look like this.

function(a, b, d, ..., first=" hey")

During function call in this case, you must provide 3 mandatory arguments first, then you can have as many arguments you want that are part of the list(...), and argument first is optional, but if you don't provide value for argument first, that argument is going to hold default value that we have provided during function definition "hey"

If you want function that returns some value, in function scope, you will have to provide return statement as the last line of that scope.

a <- function(){

    return('value to be returned')

}


Video tutorial link below.



No comments:

Post a Comment