1 Introducing the R System
1.1 Introduction
This chapter introduces the R system to the new R user. The Windows operating system is emphasized but most of the material covered also applies to other operating systems after allowing for the requirements of the particular operating system in use. Users with some experience with R should quickly glance through this chapter making sure they have mastered all topics covered here before proceeding with the main tutorial starting with Chapter 2.
In the computer age statistics has become inseparable from being able to write computer programs. Therefore, let us start with a reminder of the Fundamental Goal of S:
Conversion of an idea into useful software
The challenge is to pursue this goal keeping in mind the Mission of R (Chambers, 2008):
… to enable the best and most thorough exploration of data possible
and its Prime Directive (Chambers, 2008):
… places and obligation on all creators of software to program in such a way that the computations can be understood and trusted.
1.2 Downloading the R system
To download R to your own computer: Navigate to …/bin/windows/base and save the file R-x.y.z.-win.exe on your computer. Click this file to start the installation procedure and select the defaults unless you have a good reason not to do so. If you select ‘Create desktop icon’ during the installation phase, an icon similar to the one below should appear on the desktop. Alternatively, you can find R under All Applications.

The core R system that is installed includes several packages. Apart from these installed packages several thousands of dedicated contributed packages are available to be downloaded by users in need of any of them.
1.3 A quick sample R session
Click the R icon created on your desktop to open the Commands Window or Console. Notice the R prompt > waiting for some instruction from the user.
- At the R prompt
>enter5 – 8. We will follow the following convention to write instructions:
5 - 8
#> [1] -3- Repeat (a) but enter only 5 – and see what happens:
The above + is the secondary R prompt. It indicates that an instruction is unfinished. Either respond by completing the instruction or press the Esc key to start all over again from the primary prompt.
- Enter
xx <- 1:10This instruction creates an R object with name (or label) xx containing the vector
(1, 2, 3, 4, 5, 6, 7, 8, 10).
- Enter
yy <- rnorm(n = 20, mean = 50, sd = 15) This instruction creates an R object with name yy containing a random sample of 20 values from a normal distribution with a mean of 50 and a standard deviation of 15.
- Enter
xx
#> [1] 1 2 3 4 5 6 7 8 9 10The above example shows that when the name of an R object is entered at the prompt, R will respond by displaying the contents of the object.
Obtain a representation of the contents of the object
yycreated in (d).-
A program in R is called a function. Any function in R is also an R object and therefore has a name (or label). It follows from (e) that if the name of a function is entered at the prompt, R will respond by displaying the contents of the function.
How then can an R function be executed i.e. how can an R function be called? Apart from its name an R function has a list of arguments enclosed within parentheses. An R function is called by entering its name followed by a list of arguments enclosed within parentheses. As an example, let us calculate the mean of the object
yycreated above by calling the functionmean:
mean(yy)
#> [1] 56.11367Note that the prompt appear followed by the mean of object yy.
Objects created during an R session in the workspace are stored in a database .RData in the current folder. A listing of all the objects in a database can be obtained by calling the functions
ls()orobjects(). Now, first enter, at the R prompt, the instructionobjects(orls) and then the instructionobjects()(orls()). Explain what has happened.Objects can be removed by the following instruction:
rm(name1, name2, ... ).Apart from the console there are several other types of windows available in R e.g. graphs are displayed in graph windows. To illustrate, enter the following instructions at the R prompt in the console or commands window:

These instructions have resulted in the opening of a graph window containing the required histogram and the user can switch from the console to the graph window and back again to the console.
- The R session can be terminated by closing the window or entering
q()at the R prompt. Either way the user is prompted to save the workspace. If the user chooses not to save, all objects created during the session are lost.
1.4 Working with RStudio
Many users of R prefer working with RStudio. RStudio is a free and open source integrated development environment for R which works with the standard version of R available from CRAN. It can be downloaded from the RStudio home page to be run from your desktop (Windows, Mac or Linux). Full details about the functionality of RStudio are available from its home page. Here, only a brief introduction to RStudio is given.
When RStudio is installed on your computer the following icon is created on the desktop:

Clicking the above icon open the RStudio development environment as shown in Figure 1.1. In order to open any R workspace with RStudio drag the corresponding .RData file to the above RStudio icon and drop it as soon as ‘Open with RStudio’ becomes visible.

Figure 1.1: The RStudio development environment for R.
The bottom left-hand panel is the familiar R console.
The bottom right-hand panel is used for : (a) a listing of the files in the folder where the workspace (.RData) for the active project is kept (b) a listing of all installed packages available to be attached to the search path as well as menus for installing and updating packages (c) the graph windows (if any) (d) the Help facilities.
The top left-hand panel can be used for creating and managing script files (see 1.9.1) while the top right-hand panel provides information on the objects in the current folder as well as the history of previous commands given in the console.
1.5 R: an interpretive computer language
Essentially, in an interpretive language instructions are given one by one. Each instruction is then evaluated or interpreted in turn by an internal program called an interpreter or evaluator and some immediate action is taken. For example, the instruction given in 1.3(a) is evaluated by the R evaluator resulting in the answer –3 being returned. On the other hand, in 1.3(b) the evaluator found the instruction to be incomplete and therefore asked for more information.
An advantage of an interpretive language is that intermediate results can be obtained quickly without having first to wait for a complete program to finish as is the case with a compiler language. In the latter case a complete program is translated (or compiled) by a program called a compiler. The compiled program can then be converted to a standalone application that can be called by other programs to perform a complete task. In general compiler languages handle computer memory relatively more efficiently and calculations are executed more speedily. Communication with the R evaluator takes place through a set of instructions called escape sequences. These escape sequences take the form of a backslash preceding a character. Examples of such escape sequences are:
\n new line
\r carriage return
\t go to next tab stop
\b backspace
\a bell
\f form feed
\v vertical tab
A consequence of the above role of the backslash in R is that a single backslash in a filename will not be properly recognized. Therefore, when referring in R to the following file path “c:\My Documents\myFile.txt” all backslashes must be entered as double backslashes i.e. "c:\\My Documents\\myFile.txt" or as "c:/My Documents/myFile.txt".
1.5.1 Exercise
The cat() function can be used to write a text message to the console. Initialize a new R session and investigate the results of the following R instructions:
cat("aaa bbb")
cat("aaa bbb \n")
cat("aaa \n bbb \n")
cat("aaa \nbbb \n")
cat("aaa \t\t bbb \n")
cat("aaa\b\b\bbbb \n")
cat("aaa \n\a bbb \a\n")
cat("1\a\n"); cat("2\a\n")What is the purpose of the semi-colon in the line above?
Could you distinguish the two soundings of the bell? Try the following:
Could you now distinguish the two soundings of the bell?
What is the purpose of the Sys.sleep() instruction?
1.6 Accessing the Help functionality
- Use
?meanto obtain help on the usage of the R function mean().
- Find out what is the difference between the instructions
?meanand
??mean- What help is available via the instruction
- Use
?help.search()to find out how to obtain help using the R function help.search(xx). Note: For hep on an operator or reserved word quotes are needed, e.g.
?matrixbut
?"?"or
?"for"1.7 More R basics
R as an interactive language allows for fast acquisition of results.
R is a functional language in two important senses: In a more technical sense it means the R model of computation relies more on function evaluation than by procedural computations and changes of state. The second sense refers to the way how users communicate to R namely almost entirely through function calls.
R as an object-oriented language refers in a technical sense to the S4 or S5 type of objects with their associated classes and methods as mentioned in the Preface. In a less technical sense it means that everything in R is an object.
R objects will be studied in detail in later chapters. What is important for now, is the following:
- Everything in R is an object.
- There are different types of objects e.g. function objects, data objects, graphics objects, character objects, numeric objects.
- Usually objects are stored in the current folder called the Global environment; recognized by R under the name
.GlobalEnvand available in the file system under the name .RData. - Objects are created from the console by assignment through the instruction
name <- objector
object <- name- In R names are case sensitive i.e. peter and Peter are two different objects.
- Objects created by assignment during an R session are stored permanently in the Global environment (working directory) unless the user chooses not to save when terminating an R session.
- Care must be exercised when creating a new object by assignment: if an object with the name my.object already exists in the Global environment and a new object is created by assigning it to the name my.object then the old my.object is over-written and it is replaced by the new object without any warning.
- Remember the way the R evaluator operates: if an object name is given at the R prompt the R evaluator responds by displaying the content of the object. Review the difference between the instructions
qand
q()- The symbol
#marks a comment. Everything following a#on a line is ignored by the R evaluator. Check for example the result of the instruction
5+8 # +12
#> [1] 13Usage of the symbols
<-,=and==. The symbol<-is used for assigning the object on its right-hand side to a name (label) on its left-hand side; the equality sign=is used for specifying the arguments of functions while the double equality symbol==is used for comparison purposes. In earlier versions of R these rules were strictly applied by the R evaluator. However, in recent versions of R the evaluator allows the equality sign also in the case for assigning an object to a name. We believe that reserving the equality sign only for argument specifications in functions leads to more clarity when writing complex functions and therefore we discourage its usage for creating objects by assignment. In this book creating objects by assignment will be exclusively carried out with the assignment symbol<-.The symbol
->assigns the object on its left-hand side to the name (label) on its right-hand side.Working with packages: The core installation includes several packages. To see them issue the command
search()from the R prompt in the console. Notice that the first object in the search list is.GlobalEnv. This is followed by other objects. Packages are recognized by the string package followed by a colon and the name of the package. In order for a package to be used the following steps must be followed: if the package has been installed previously it needs only to be loaded into the search path using the commandlibrary(packagename)from the R prompt. This will load the package by default in the second position on the search path. If the package has not been installed previously it must first be installed. This is most easily done using the top menu Packages. The commandrequire(packagename)appears to be identical tolibrary(packagename). The functionrequire()is designed for use inside other functions as it gives a warning, rather than an error, if the package does not exist.More on the help (
?) facility: Table 1.1 contains details about help available for some special keywords.
| Help query | Explanation |
|---|---|
?Arithmetic |
Unary and binary operators to perform arithmetic on numeric and complex vectors |
?Comparison |
Binary operators for comparison of values in vectors |
?Control |
The basic constructs for control of the flow in R instructions |
?dotsMethods |
The use of the special operator ...
|
?Extract |
Operators to extract or replace parts of vectors, matrices, arrays and lists |
?Logic |
Logical operators for operating on logical and numeric vectors |
?.Machine |
Information on the variable .Machine holding information on the numerical characteristics of the machine R is running on |
?NumericConstants |
How R parses numeric constants including Inf, NaN, NA
|
?options |
Allow the user to set and examine a variety of global options which affect the way in which R computes and displays its results |
?Paren |
Parentheses and braces in R |
?Quotes |
Single and double quotation marks. Back quote (backtick) and backslash for starting an escape sequence |
?Reserved |
Description of reserved words in R |
?Special |
Special mathematical functions related to the beta and gamma functions including permutations and combinations |
?Syntax |
Outlines R syntax and gives the precedence of operators |
1.8 Regular expressions in R: the basics
It follows from 1.7(d) that care must be taken when objects are assigned to names. Furthermore, the Global environment or any other R database may easily contain hundreds of objects. Therefore, a frequent task is to search for patterns in the names of objects e.g. searching for all object names starting with “Figure” or ending in “.dat”. The R function objects() or ls() has arguments pos and pattern for specifying the position of a database to search and a pattern of characters appearing in a name (or string), respectively. The pattern argument can be given any regular expression. Regular expressions provide a method of expressing patterns in character values and are used to perform various tasks in R. Here we are only considering the task of extracting certain specified objects in a database using the pattern argument of objects() or ls().
The syntax of regular expressions follows different rules to the syntax of ordinary R instructions. Moreover its syntax differs depending on the particular implementation a program uses. By default, R uses a set of regular expressions similar to those used by UNIX utilities, but function arguments are available for changing the default e.g. by setting argument perl = TRUE.
Regular expressions consist of three components: single characters, character classes and modifiers operating on single characters and character classes.
Character classes are formed by using square brackets surrounding a set of characters to be matched e.g. [abc123], [a-z], [a-zA-Z], [0-9a-z]. Note the usage of the dash to indicate a range of values.
The modifiers operating on characters or character classes are summarized in Table 1.2.
| Modifier | Operation |
|---|---|
^ |
Expression anchors at beginning of target string |
$ |
Expression anchors at end of target string |
. |
Any single character except newline is matched |
| |
Alternative patterns are separated |
( ) |
Patterns are grouped together |
* |
Zero or more occurrences of preceding entity are matched |
? |
Zero or one occurrences of preceding entity are matched |
+ |
One or more occurrences of preceding entity are matched |
{n} |
Exactly n occurrences of preceding entity are matched |
{n,} |
At least n occurrences of preceding entity are matched |
{n, m} |
At least n and at most m occurrences of preceding entity are matched |
Because of their role as modifiers or in forming character classes the following characters must be preceded by a backslash when their literal meaning is needed:
[ ] { } ( ) ^ $ . | * + \
Note that in R this means that whenever one of the above characters needs to be escaped in a regular expression it must be preceded by double backslashes. Table 1.3 contains some examples of regular expressions.
| Regular expression | Meaning |
|---|---|
"[a-z][a-z][0-9]" |
Matches a string consisting of two lower case letters followed by a digit |
"[a-z][a-z][0-9]$" |
Matches a string ending in two lower case letters followed by a digit |
"^[a-zA-Z]+\\." |
Matches a string beginning with any number of lower or upper case letters followed by a period |
"(ab){2}(34){2}$" |
Matches a string ending in abab3434
|
1.8.1 Exercise
Initialize an R session
- Attach the MASS package in the second (the default) position on the search path by issuing the command
- Get a listing of all the objects in package MASS by requesting
objects(pos=2)- Explain the difference between
objects(pos=2, pat=".")andobjects(pos=2, patt="\\."). - Obtain a listing of all objects with names starting with three letters followed by a digit.
- Obtain a listing of all objects with names ending with three letters followed by a digit.
- Obtain a listing of all objects with names ending in a period followed by exactly three or four letters.
1.9 From single instructions to sets of instructions: introducing R functions
Consider the following problem: the R data set sleep contains the extra hours of sleep of 20 patients after a drug treatment. Suppose this data set can be considered a sample from a normal population. A 95% confidence interval is required for the mean extra hours of sleep. It is known that the confidence interval is given by \(\left[ \mathbf{\bar{x}}- \left( \frac{s}{\sqrt(n)} \right) t_{n-1,0.025}; \mathbf{\bar{x}}+ \left( \frac{s}{\sqrt(n)} \right) t_{n-1,0.025} \right]\). This problem can be solved by entering the following instructions one by one:
sleep.data <- sleep[ ,1]
sleep.mean <- mean(sleep.data)
sleep.sd <- sd(sleep.data)
t.perc <- qt(0.975,19)
left.boundary <- sleep.mean - (sleep.sd/sqrt(length(sleep.data)))*t.perc
right.boundary <- sleep.mean + (sleep.sd/sqrt(length(sleep.data)))*t.perc
cat ("[", left.boundary, ";", right.boundary, "]\n")
#> [ 0.5955845 ; 2.484416 ]In situations like the above, the problem can be addressed using a script file or writing a function. We are going to introduce two methods for writing functions in R:
- using a script file and
- using the function
fix().
1.9.1 Writing an R function using a script file
- From the R top menu select File; New script. A script window will open with a simultaneous change in the menu bar.
- Type the instructions in the script window.
- Select all the typed text and run the script by clicking the run icon (or Ctrl+R).
- Note what is shown in the R console window.
- Script files are ordinary text files. They can be saved, edited and opened using any text editor.
- By convention R script files have the extension xxxx.r.
- Next, change the spelling in the last two lines from
right.boundarytoRight.boundary. Select all the text and run the script. Check the output appearing on the console. - Script windows can also be used for creating an R function.
- Create an R function by changing the text as shown below.
conf.int <- function (x = sleep[,1])
{
x.mean <- mean(x)
x.sd <- sd(x)
t.perc <- qt(0.975,19)
left.boundary <- x.mean - (x.sd/sqrt(length(x)))*t.perc
right.boundary <- x.mean + (x.sd/sqrt(length(x)))*t.perc
list (lower = left.boundary, upper = right.boundary)
}- Select the text and notice what happens in the R commands window (the console).
- Give the instruction
objects()at the R prompt. What has happened? - You can now run the function from the commands window (the console) by typing:
conf.int (x = sleep[,1])
#> $lower
#> [1] 0.5955845
#>
#> $upper
#> [1] 2.484416If you want to create and run the function
conf.intin a script window then add the instructionconf.int (x = sleep[,1])as the last line in the script window. Now, select only this line and run it. Check the R console.What will happen if a syntax error is made in the script window? Change the code in the script file as follows, deliberately deleting the last closing parenthesis in the last line of the function.
conf.int <- function (x = sleep[,1])
{
x.mean <- mean(x)
x.sd <- sd(x)
t.perc <- qt(0.975,19)
left.boundary <- x.mean - (x.sd/sqrt(length(x)))*t.perc
right.boundary <- x.mean + (x.sd/sqrt(length(x)))*t.perc
list (lower = left.boundary, upper = right.boundary
}
conf.int (x = sleep[,1])- Select only the final line and run it. Check the R console. No problem, the function executed correctly. This is because the code for
conf.intin the script file was changed, but the updated object was not created by running it in the console. - Select all the code in the script and run it. Check the R console. Discuss.
1.9.2 Writing an R function using fix()
When using fix() the built-in R text editor can be used when using script files but in the windows environment notepad or preferably notepad++ or Tinn-R is preferred.
The following instruction is necessary for changing the default editor to be used with fix():
options(editor = "notepad")or
options(editor = "full path to the relevant exe file")- Enter
fix (my.func)at the R prompt. A text editor will open. Type the instructions as shown below.
function (x = sleep[,1])
{
x.mean <- mean(x)`
x.sd <- sd(x)
t.perc <- qt(0.975,19)
left.boundary <- x.mean - (x.sd/sqrt(length(x)))*t.perc
right.boundary <- x.mean + (x.sd/sqrt(length(x)))*t.perc
list (lower = left.boundary, upper = right.boundary)
}Close the window. Check what happens in the R console.
You can now run the function from the commands window (the console) similar to in 1.9.1(l), but changing the name of the function from conf.int to my.func.
What will happen if a syntax error is made when using fix? At the R prompt type
fix (my.func). Make a deliberate syntax error, e.g. delete the last closing brace. Close the text editor window. What happens in the console? What is to be done to correct the mistake?Carefully study the message in the R console when a syntax error occurred in a function created by
fix():
> Error in edit(name, file, title, editor) :
unexpected 'yyy' occurred on line xx
use a command like
x <- edit()
to recover- The following is the correct way to respond to the above message from the R evaluator:
my.func <- edit()If you simply use fix(my.func) at this point, the R and the editor will revert to the version of the function before the previous edit.
WARNING
Before writing a function for solving any problem: make sure the problem is understood exactly; make 100% sure the relevant statistical theory is understood correctly. Failure to do so is careless and dangerous!
1.10 R Projects
The different windows in R are the Data window, Script window, Graph window and Menus and Dialog windows. The current workspace in R is .GlobalEnv. The function getwd() is used to obtain the path to the current folder’s .Rdata and .Rhistory.
Note: In order to see the files .Rdata and .Rhistory being displayed as such, it may be necessary to turn off the option “Hide extensions for known file types” in Windows Explorer.
It is important to make provision for different workspaces associated with different projects. In R, different .Rdata files in different folders would separate different projects. There is however much to gain in using Projects in RStudio.
1.10.1 Creating a project in RStudio
From the top menu, select File, New Project. Follow the prompts to create a new project, either in an existing folder or creating a new folder for your project, say MyProject.
Navigate to the folder MyProject in Windows Explorer.
Notice a file MyProject.Rproj has been created in the folder.
By double-clicking on this file you open the project in RStudio. The advantages of opening the project this way are:
your workspace from the file MyProject.Rdata is automatically loaded
by placing any related files like data set in the folder MyProject or a subfolder, say MyProject\data means that in your code you only have to use relative folder references, i.e. refer to MyProject\mydata.xlsx or MyProject\data\mydata.xlsx instead of something like c:\users\myname\Documents\MyProject\data\mydata.xlsx.
the major advantage of relative references is that it is not specific to the computer and makes porting between devices possible
sharing your project with a collaborator will simply entail copying the entire contents of the MyProject folder.
1.11 A note on computations by a computer
When writing R functions it is important to keep in mind that the way computations are performed by a computer are not always according to the rules of algebra. Two important occurrences are given below.
In mathematics the following statement is incorrect:
x = x + kfor \(k \neq 0\) but in computer programming the statementx = x + kis legitimate and it meansxis replaced byx + k.In general, the treatment of integers and real numbers for which R uses floating point representation happens at a fundamental level over which R has no control. Real numbers cannot necessarily be exactly represented in a computer – some can only be approximated. Furthermore, there are limitations to the minimum and maximum numbers that can be represented in a computer. This might lead to what is known as underflow or overflow. A more detailed discussion appears in a later chapter.
Open an R session and issue the command
.Machinefor details about the numerical environment of your computer.
1.12 Built-in data sets in R
R contains several built-in data sets collected in the package datasets. This package is automatically attached to the search path. Type ?datasets at the R prompt for details. Apart from these data sets several other data sets from other packages are also used in this book.
1.13 The use of .First() and .Last()
The function .First() is executed at the beginning of every R session. This only works in R and not in RStudio.
Instead of having to specify
options(editor = "notepad")each time an R session is initialized, create the following function and save in the .Rdata before exiting R.
.First <- function() { options(editor = "notepad") }to ensures that Notepad is the text editor during any subsequent session.
Similar to .First() the function .Last() can be created for execution at the end of an R session.
1.13.1 Security: an example of the usage of .First()
The .First() facility can be used to prevent access to a R workspace by setting a password protection. This can be done as follows:
Create a new workspace for running the example on security. In this workspace create the following R function
password <- function() # Note the structure of a function
{ cat("Password? \n")
password <- readline() # What is the usage of readline()?
if (password != "PASSWORD")
q(save="no") # The meaning of != is "not equal to"
else (cat("You can proceed \n"))
} Now create the function:
.First <- function()
{ # What must you be careful of?
password()
}- Terminate your R session and open it again.
- Discuss the construction and usage of the above functions.
- Can you break the above security?
- Can you make changes to the above security to make it more safe?
1.15 Creating PDF and HTML documents from R output: R Markdown
The R package knitr is used to obtain reproducible results from R code in the form of .pdf or .html documents. In addition to knitr, R Markdown can be used to create .html, .pdf or even MS Word documents. Markdown is a so-called markup language with plain-text-formating syntax. An R Markdown document is written in markdown and contains chunks of embedded R code. Although the render() function in the package rmarkdown can be used (similar to the knit() function from the package knitr), to create the output document from the R Markdown .Rmd file, R Markdown is typically used in conjunction with RStudio. In the top menu, select File, New File, R Markdown… to open the example.Rmd file providing the user with the structure of an R Markdown file. For our illustration, we will select the output format as .html.
Edit the example.Rmd file to contain the following:
---
title: "An Illustration of Some Capabilities of R Markdown"
author: "Niel le Roux and Sugnet Lubbe"
date: "22/01/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Short description
Code chunks in .Rmd files are delimited with ` ```{r} ` at the top where a chunk
label and any chunk options can appear and ` ``` ` at the end. In-line R code
chunks are indicated with single ` `r ` on either side.
*****
Here is an example containing several chunks of code. Note that in the first
chunk R code is not shown due to the option `echo = FALSE`. In the remaining
chunks R code is shown due to the option above 'echo = TRUE'.
_Note R code not shown for this chunk._
```{r y, echo=FALSE}
y <- 1
y
```
```{r rnorm}
require(lattice)
set.seed(123)
x <- rnorm(1000, 20, 5)
```
We analyse data drawn from $\mathcal{N}(20,25)$. The mean is
`r round(mean(x),3)`. The following code shows the distribution via a histogram
```{r histexample}
hist(x)
```
and the code below via a boxplot.
```{r boxexample}
boxplot(x)
```
The first element of \texttt{x} is `r x[1]`. Note the usage of ` \texttt{x} `
above.
*two plots side by side (option fig.show='hold')*
```{r side-by-side, fig.show='hold', out.width="50%"}
par(mar=c(4,4,0.1,0.1), cex.lab=0.95, cex.axis=0.9, mgp=c(2,0.7,0),
tcl=-0.3, las=1)
boxplot(x)
hist(x,main="")
```
```{r linear_model}
n <- 10
x <- rnorm(n)
y <- 2*x + rnorm(n)
out <- lm(y ~ x)
summary(out)$coef
```At the top of the text editor, click on Knit to create the .html document. Note that with the down arrow, options Knit to PDF and Knit to Word can also be chosen. The output format is also specified in line 5 of the text file with output: html_document. Had we chosen .pdf as output format, it would be output: pdf_document. Typically, R Markdown is used for reporting, directly incorporating the R code and output. For more formal documents with Figure and Table caption references, tables of content, etc. the R package bookdown should be used. Install the package and replace the output statement with output:bookdown::pdf_document2. For more information on the use of bookdown, click here.
1.16 Command line editing
Commands given in an R session are stored together with commands given in previous sessions in a file .History in the same folder as the .RData file. In an R session previous commands can be retrieved at the R prompt by pressing the up and down arrow keys. A previous command can then be edited using the backspace, delete, home, end keys as well as the shortcuts for copy and paste.