Download presentation
Presentation is loading. Please wait.
Published bySilje Gulbrandsen Modified over 6 years ago
1
Writing Functions in R Introduction to R, Part II
Anna Blackstock Statistician, Biostatistics and Information Management Office (BIMO) NCEZID/DFWED
2
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.
3
Anatomy of Creatures in the Land of R: Functions
( ) arguments { } From Beau Bruce’s PowerPoint presentation “functions.” instructions output
4
input data ( ) function {} output data
5
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?
6
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!
7
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?
8
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?
9
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 and “Expressing Yourself with R” at (licensed under Creative Commons Attribution-Noncommercial 3.0 United States License).
10
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.”
11
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:
12
References R for Data Science book by Grolemund and Wickham:
Hadley Wickham’s “Expressing Yourself with R” presentation: Licensed under Creative Commons Attribution-Noncommercial 3.0 United States License.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.