Writing Functions in R Introduction to R, Part II Anna Blackstock Statistician, Biostatistics and Information Management Office (BIMO) NCEZID/DFWED
What are functions? “Functions in R are objects that carry out operations on arguments … and return one or more values.” Syntax: From “The R Book” by Michael J. Crawley, Wiley Publishing, 2007.
Anatomy of Creatures in the Land of R: Functions ( ) arguments { } From Beau Bruce’s PowerPoint presentation “functions.” instructions output
input data ( ) function {} output data
Example of an R Function Take a look at this function: What are the arguments? What does this function do? What is a better name for this function?
When should you write functions? Functions can save you time and prevent copy/paste errors if you are repeating a task. Rule of thumb: any time you will do something > 3 times, think about writing a function!
How to Get Started Would it be easier to: Write a general function, and then try to apply it to a particular problem, or Write code to solve a particular problem, and then generalize it so that it can be used many times?
How to Get Started Would it be easier to: Write a general function, and then try to apply it to a particular problem, or Write code to solve a particular problem, and then generalize it so that it can be used many times?
How to Get Started Would it be easier to: Write a general function, and then try to apply it to a particular problem, or Write code to solve a particular problem, and then generalize it so that it can be used many times? Advice: the best way to start writing a function is to NOT start writing a function. See http://r4ds.had.co.nz/functions.html and “Expressing Yourself with R” at http://bit.ly/hadley-express-yourself (licensed under Creative Commons Attribution-Noncommercial 3.0 United States License).
General Rules for Writing Functions Solve the problem before trying to write a function. Give your function an appropriate name. Make sure your function is correct and know when it fails. Reserve comments for the “why.”
Where to from here? If you’d like to learn more, this interactive course (taught by siblings Hadley and Charlotte Wickham) might be a good place to start: https://www.datacamp.com/courses/writing-functions-in-r
References R for Data Science book by Grolemund and Wickham: http://r4ds.had.co.nz/functions.html Hadley Wickham’s “Expressing Yourself with R” presentation: http://bit.ly/hadley-express-yourself Licensed under Creative Commons Attribution-Noncommercial 3.0 United States License.