Chapter 2. Some Basics

Introduction

The recipes in this chapter lie somewhere between problem-solving ideas and tutorials. Yes, they solve common problems, but the Solutions showcase common techniques and idioms used in most R code, including the code in this Cookbook. If you are new to R, I suggest skimming this chapter to acquaint yourself with these idioms.

2.1. Printing Something

Problem

You want to display the value of a variable or expression.

Solution

If you simply enter the variable name or expression at the command prompt, R will print its value. Use the print function for generic printing of any object. Use the cat function for producing custom formatted output.

Discussion

It’s very easy to ask R to print something: just enter it at the command prompt:

> pi
[1] 3.141593
> sqrt(2)
[1] 1.414214

When you enter expressions like that, R evaluates the expression and then implicitly calls the print function. So the previous example is identical to this:

> print(pi)
[1] 3.141593
> print(sqrt(2))
[1] 1.414214

The beauty of print is that it knows how to format any R value for printing, including structured values such as matrices and lists:

> print(matrix(c(1,2,3,4), 2, 2))
     [,1] [,2]
[1,]    1    3
[2,]    2    4
> print(list("a","b","c"))
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

This is useful because you can always view your data: just print it. You needn’t write special printing logic, even for complicated data structures.

The print function has a significant limitation, however: it prints only one object ...

Get R Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.