How to write your own functions

How to write your own functions

Yeah! One of the best features of R! Functions!

As you have seen (and might have noticed), R has been created with two things in mind. First, vectors. Everything can be expressed through vectors, and is handled as such. Even when it’s a matrix, columns will pretty much be handle as vectors. Second, functions! Here, the point is to perform statistical analyses and other dark magic. The data are here; we just need to do something with them.

Through the previous classes, you have -hopefully- grown more and more accustomed to functions and how to use them. But just as a quick reminder, let me state the obvious, and things you probably have already grasped by now.

Work in R lies on two things: objects and functions. Objects, as you already know, are “boxes“. They are the elements containing other things (those other things being what we are interested in). Most of the time, those boxes contain data. Functions are small (or incredibly huge) factories that will take the box you input them with and do something with it. Modify it, create something from it, simply read it, etc. Of course, functions have to be contained somewhere. And therefore, functions are also technically objects. But the fact that they can take an object and do something with it makes them special.

Now, I should remind you that functions (most of the time) don’t actually modify and replace the element that was inputted. They will just do their job, and be done with it. If you want to save the result of the operations performed by the function, you’ll have to save it in an object. We have done that every time so far, but it’s always good to point it out again.

FUNCTION, THE GENERAL STRUCTURE

Need your work to function? Know how functions work!

CREATING SEQUENCES OF NUMBER

You'll never have to count by yourself again!

CONCLUSION

And they lived happily ever after! The End!

LET’S GET LOGICAL

Learn more about what's true, false, logical tests and how to use them.

FUNCTION: IN THE LOOP

How to iterate, repeat, recur.