Class Notes from Chapter 1

This is a R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

Further References

Link to Advanced R

The Art of R Programming by Norman Matloff is the engine for programming in R. It is a comprehensive guide to R programming and covers topics such as data structures, control structures, functions, and object-oriented programming.

  • Italic set text wrapped between * * or _ _
  • Bold text wrapped between ** ** 0r __ __
  • Subscript text wrapped between ~ ~
  • Superscript text wrapped between ^ ^
  • Strikethrough text wrapped between ~~ ~~

Header 1

Header 2

How to insert image
How to insert image

Use the plain http address or add link to a phrase

Tables can be created using the pipe symbol | and hyphens - to separate the header row from the data rows. For example create a table with three columns and two rows:

Header 1 Header 2 Header 3 Header 4
Row1, Column 1 Row 1, Column 2 Row 1, Column 3 Martin Sato
Row 2, Column 1 Row 2, Column 2 Row 2, Column 3 Beverley Ogenche

For example lets create class list with surnames

First name Surname Age Gender
Martin Sato 30 Male
Beverley James 28 Female

How can we use the kable package to create a table in R Markdown? The kable() function from the knitr package can be used to create tables in R Markdown. Which will be covered later.

Code Chunks

There are two possibilities to include R code in the document.

The First is to use inline R code , which is a single line of R code that is executed and the result is included in the output document. r (wrapped between is used to indicate inline R code. For example, the following code chunk calculates the mean of the mpg variable in the mtcars dataset and includes the result in the output document:

The average fuel efficiency is 20.090625 miles per gallon.

The second is to use a code chunk, which is a block of R code that is executed and the results are included in the output document.

You can include R code in the document as follows:

mean(mtcars$mpg)
## [1] 20.09062

Chunk options:control what shows

You often dont’t want to see the code in the output document, but you want to see the results. You can use the echo option to control whether the code is displayed in the output document. For example, the following code chunk calculates the mean of the mpg variable in the mtcars dataset and includes the result in the output document, but does not show the code:

## [1] 20.09062

The above code chunk will result in the following output:

# [1] 20.09062

To remove the # from the output we use comment= ’ ’

  [1] 20.09062

Quick Comparison

Setting Code shown? Result shown?
echo=TRUE Yes Yes
echo=FALSE No Yes
include=FALSE No No (but the code still runs)
eval=FALSE Yes No (the code is not run)
results=‘hide’ Yes No (the code is run, but the results are not shown)
warn=FALSE Yes Yes (but warnings are not shown)
message=FALSE Yes Yes (but messages are not shown)

Figure Allignment

  1. fig.height: (Numeric) Height of the plot window in R
  2. fig.width: (Numeric) Width of the plot window in R
  3. fig.dim: Vector of resp. the fig.width and fig.height
  4. fig.asp: (Numeric) Aspect ratio of the plot window in R
  5. fig.align: Alignment of the plot in the report:
    1. 'left'
    2. 'center'
    3. 'right'
  6. fig.keep: Which images to keep as single plots: 1.'high': Keep only the high-level plots (i.e. integrate all low level commands in one plot)
    1. 'none': Keep no plots
    2. 'all': Keep all plots (i.e. low-level commands produce different plots)
    3. 'first': Keep only the first plot
    4. 'last': Keep only the last plot

Numeric sequence number of the plot to keep

  1. fig.show: How to arrange the plots in the report: 1.'asis': Show the plots as they appear in R

    1. 'hold': Show all plots together at the end of the chunk
    2. 'animate': Integrate all plots into an animation
    3. 'hide': do not show the plots in the report
  2. out.height: Height of the plot in the report: '8cm' '300px'

  3. out.width: Width of the plot in the report: '3cm' '60%'

  4. dev: Graphical device to use (e.g. dev = ‘png’)

  5. dev.args: List of arguments for the graphical device

  6. dpi: Dots per inch (default = 72)

For example, the following code chunk creates a scatter plot of the wt and mpg variables in the mtcars dataset and centers the plot in the output document:

plot(mtcars$wt, mtcars$mpg, main = "Scatter plot of wt vs mpg", xlab = "Weight", ylab = "Miles per gallon")

Let’s examine the relationship between speed and stopping distance using a linear regression model: It can created by sandwiching the following between two $ $ sign

Y = \beta_0 + \beta_1 X + \epsilon

\(Y = \beta_0 + \beta_1 X + \epsilon\).

par(
  mar = c(4, 4, 1, 1), 
  mgp = c(2, 1, 0), 
  cex = 0.8
  ) # this code sets the margins, axis label positions, and text size for the plot

plot(
  cars,pch = 20, col = "blue", 
  main = "Scatter plot of speed vs dist", 
  xlab = "Speed (mph)", 
  ylab = "Stopping distance (ft)"
  ) # this code creates a scatter plot of the speed and stopping distance variables in the cars dataset, with blue points and appropriate axis labels

fit <- lm(dist ~ speed, data = cars)
abline(fit, col = "red", lwd = 2)

The slope of the simple linear regression is 3.9324088 and the intercept is -17.5790949. The R-squared value is 0.6510794.

Or

coef(fit)[2] # slope
     speed 
  3.932409
coef(fit)[1] # intercept
  (Intercept) 
    -17.57909
summary(fit)$r.squared # R-squared value
  [1] 0.6510794
  • cache means save and reuse the results of a code chunk.

- ref.label tells RMarkdown to rerun the code from another named chunk

Analogy: saying “see page 12” instead of copying the text again.

First, give a chunk a name (the label right after r). Then another chunk can rerun that code with ref.label. {r my_plot, eval=FALSE}

plot(mtcars$wt, mtcars$mpg, main = "Scatter plot of wt vs mpg", xlab = "Weight", ylab = "Miles per gallon")

Some text explaining the idea…. {r my_plot2, ref.label='my_plot'}

  • child allows you to insert another RMarkdown source file into the current report.

  • engine specifies the programming language used to execute the chunk.

Elegant Code

https://style.tidyverse.org

https://google.github.io/styleguide/Rguide.html

https://contributions.bioconductor.org/r-code.html

Appendix: all code

knitr::opts_chunk$set(echo = TRUE)
mean(mtcars$mpg)
mean(mtcars$mpg)
mean(mtcars$mpg)

plot(mtcars$wt, mtcars$mpg, main = "Scatter plot of wt vs mpg", xlab = "Weight", ylab = "Miles per gallon")
par(
  mar = c(4, 4, 1, 1), 
  mgp = c(2, 1, 0), 
  cex = 0.8
  ) # this code sets the margins, axis label positions, and text size for the plot

plot(
  cars,pch = 20, col = "blue", 
  main = "Scatter plot of speed vs dist", 
  xlab = "Speed (mph)", 
  ylab = "Stopping distance (ft)"
  ) # this code creates a scatter plot of the speed and stopping distance variables in the cars dataset, with blue points and appropriate axis labels

fit <- lm(dist ~ speed, data = cars)
abline(fit, col = "red", lwd = 2)

coef(fit)[2] # slope

coef(fit)[1] # intercept

summary(fit)$r.squared # R-squared value

plot(mtcars$wt, mtcars$mpg, main = "Scatter plot of wt vs mpg", xlab = "Weight", ylab = "Miles per gallon")