Chapter 2. Some Basics
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, we suggest skimming this chapter to acquaint yourself with these idioms.
2.1 Printing Something to the Screen
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.14
sqrt
(
2
)
#> [1] 1.41
When you enter expressions like these, R evaluates the expression and
then implicitly calls the print
function. So the previous example is
identical to this:
(
pi
)
#> [1] 3.14
(
sqrt
(
2
))
#> [1] 1.41
The beauty of print
is that it knows how to format any R value for
printing, including structured values such as matrices and lists:
(
matrix
(
c
(
1
,
2
,
3
,
4
),
2
,
2
))
#> [,1] [,2]
#> [1,] 1 3
#> [2,] 2 4
(
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 need not write special printing logic, even for complicated data
structures.
The print
function has a significant ...
Get R Cookbook, 2nd Edition 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.