It's hard to overstate the importance of functions in the R language. Pretty much everything you do in R involves calling a function. From creating objects, to doing calculations, to creating plots and fitting statistical models, everything is done by calling a function. In fact, the first R command you probably ever ran:
x <- 2 + 2
involved two function calls: though it may not look like it, <- and + are both actually functions.
If you've been using R for any length of time, there's a good chance you've started writing your own functions, either as a way to automate tasks or as a way of extending the R language itself to suit your own needs. This is a great way to get the most out of R. When writing functions, it's useful to understand the details of how functions work, how variables are referenced, accessed and passed between functions, and how you can modify functions. Hadley Wickham has created an excellent overview of functions in R (part of his in-progress Making Reproducible Code book)
- the components of a function (the formal arguments, the body, and its environment)
- lexical scoping, and the rules for how objects and other functions are found within a function
- how arguments to a function are assigned (and how missing and named arguments are handled)
- how to write "special" functions, to create your own version of operators like [ and <-
Also, if you're new to programming concepts like "scope", "closures" and "environments" you might want to check out Darren Wilkinson's blog post "Lexical scope and function closures in R" which provides a basic guide to such concepts.
github / Hadley Wickham: Functions
Comments