Skip to Content
R for Data Science
book

R for Data Science

by Hadley Wickham, Garrett Grolemund
December 2016
Beginner to intermediate
520 pages
10h 12m
English
O'Reilly Media, Inc.
Content preview from R for Data Science

Chapter 15. Functions

Introduction

One of the best ways to improve your reach as a data scientist is to write functions. Functions allow you to automate common tasks in a more powerful and general way than copying and pasting. Writing a function has three big advantages over using copy-and-paste:

  • You can give a function an evocative name that makes your code easier to understand.

  • As requirements change, you only need to update code in one place, instead of many.

  • You eliminate the chance of making incidental mistakes when you copy and paste (i.e., updating a variable name in one place, but not in another).

Writing good functions is a lifetime journey. Even after using R for many years I still learn new techniques and better ways of approaching old problems. The goal of this chapter is not to teach you every esoteric detail of functions but to get you started with some pragmatic advice that you can apply immediately.

As well as practical advice for writing functions, this chapter also gives you some suggestions for how to style your code. Good code style is like correct punctuation. Youcanmanagewithoutit, but it sure makes things easier to read! As with styles of punctuation, there are many possible variations. Here we present the style we use in our code, but the most important thing is to be consistent.

Prerequisites

The focus of this chapter is on writing functions in base R, so you won’t need any extra packages.

When Should You Write a Function?

You should consider ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R for Data Science, 2nd Edition

R for Data Science, 2nd Edition

Hadley Wickham, Mine Çetinkaya-Rundel, Garrett Grolemund
Data Science for Business

Data Science for Business

Foster Provost, Tom Fawcett
Python and R for the Modern Data Scientist

Python and R for the Modern Data Scientist

Rick J. Scavetta, Boyan Angelov

Publisher Resources

ISBN: 9781491910382Errata PageSupplemental Content