7 A Closer Look at R Programming

 

This chapter covers

  • Working with vectors and learning about R’s recycling behavior
  • Learning and reviewing some of the more essential base R functions (and getting the names of the dozens of other useful functions)
  • Writing our own functions to manipulate data
  • Writing conditional statements and understanding the logic behind control flow

In this chapter, we will take a closer look at how vectors, data frames, and tibbles work. We’ve used vectors in previous chapters but now we’ll learn about some of the ways that vectors can be generated, how numeric vectors can be used in math operations, and how we can subset them. We’ll also learn about how R, in certain cases, does something a little bit unexpected: recycling. It’s something that is often to be avoided and so we have to be fully aware of this behavior. Concerning data frames and tibbles: they are very similar but there are subtle differences that we need to know about. When using R long enough, you’ll come across both data frames and tibbles, so, we must be capable in handling both of these tabular data structures and dealing with their idiosyncrasies.

7.1       Vectors in R

7.1.1   Creating Vectors with the c() Function

7.1.2   Doing Math with Vectors and Understanding Recycling

7.1.3   Subsetting Vectors

7.2       Data Frames and Tibbles

7.2.1   Extracting Vectors from Tibbles

7.2.2   Using the summary() Function with Tibbles and Vectors

7.3       Useful Base R Functions

7.3.1   Assignment and Operators

7.3.2   Logical Operators and Set Functions

7.3.3   Comparisons

7.3.4   Math

7.3.5   Vectors, Data Frames, and Lists

7.3.6   Control Flow

7.3.7   Creating Functions

7.3.8   Working with Character Strings

7.4       Writing Our Own Functions

7.4.1   Creating our First R Functions

7.4.2   A More Realistic Scenario for Writing a Function

7.4.3   Coding Defensively and Checking Inputs within the Function Body

7.5       Summary