Skip to Content
Learning R
book

Learning R

by Richard Cotton
September 2013
Beginner to intermediate
396 pages
8h 8m
English
O'Reilly Media, Inc.
Content preview from Learning R

Chapter 6. Environments and Functions

We’ve already used a variety of the functions that come with R. In this chapter, you’ll learn what a function is, and how to write your own. Before that, we’ll take a look at environments, which are used to store variables.

Chapter Goals

After reading this chapter, you should:

  • Know what an environment is, and how to create one
  • Be able to create, access, and list variables within an environment
  • Understand the components that make up a function
  • Be able to write your own functions
  • Understand variable scope

Environments

All the variables that we create need to be stored somewhere, and that somewhere is an environment. Environments themselves are just another type of variable—we can assign them, manipulate them, and pass them into functions as arguments, just like we would any other variable. They are closely related to lists in that they are used for storing different types of variables together. In fact, most of the syntax for lists also works for environments, and we can coerce a list to be an environment (and vice versa).

Usually, you won’t need to explicitly deal with environments. For example, when you assign a variable at the command prompt, it will automatically go into an environment called the global environment (also known as the user workspace). When you call a function, an environment is automatically created to store the function-related variables. Understanding the basics of environments can be useful, however, in understanding the ...

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

Advanced R

Advanced R

Hadley Wickham
The R Book

The R Book

Michael J. Crawley
The R Book, 2nd Edition

The R Book, 2nd Edition

Michael J. Crawley

Publisher Resources

ISBN: 9781449357160Errata PageSupplemental Content