Functions are blocks of code organised together which perform a specific task.
R comes with many built-in functions which we can add to by downloading fantastic packages.
However, writing your own functions is where the true power of R lies - though it can be confusing.
1/16
In this thread I will cover:
1. When to write functions 2. How to write functions 3. Tidy evaluation 4. Passing multiple arguments with ellipsis ... 5. Error handling arguments 6. Side effects
2/16
A question I hear from newer coders is when should I actually write a function?
I follow some basic rules of thumb to decide went to turn code into a function, though it isn't an exact science.
1. The rule of 3. 2. The rule of organisation 3. The rule of testing.
3/16
1. The rule of 3
If I repeat some code 3 or more times, or I expect to, then I write a function.
Many errors enter code from copy + paste or retyping.
By calling a function many times you reduce the chances of this error, and to update code you need only change one part.
4/16
2. The rule of organisation
Often code can become long and complex.
In these cases I will split code into functions where I think this will aid readability and manageability.
Often the inside of a big for loop is a good candidate.
5/16
3. The rule of testing
Sometimes code contains calculations or small chunks that are crucial to the program or are logically complex and I want to test them individually.
In these cases I write functions.
To learn more about unit testing have a look here:
Functions are blocks of code organised together which perform a specific task.
R comes with many built-in functions which we can add to by downloading fantastic packages.
However, writing your own functions is where the true power of R lies - though it can be confusing.
1/16
In this thread I will cover:
1. When to write functions 2. How to write functions 3. Tidy evaluation 4. Passing multiple arguments with ellipsis ... 5. Error handling arguments 6. Side effects