1 Prerequisites

library(bookdown)
## Warning: package 'bookdown' was built under R version 3.6.2
library(tinytex)
## Warning: package 'tinytex' was built under R version 3.6.2
# install.packages("tinytex")
# tinytex::install_tinytex()  # install TinyTeX
# After that, check if this returns True
tinytex:::is_tinytex()
## [1] TRUE

2 First Introduction

You can label chapter and section titles using {#label} after them, e.g., we can reference Subsection 3.2.1. If you do not manually label them, there will be automatic labels anyway, e.g., Chapter 2.

Figures and tables with captions will be placed in figure and table environments, respectively.

par(mar = c(4, 4, .1, .1))
plot(pressure, type = 'b', pch = 19)
Here is a nice figure!

Figure 2.1: Here is a nice figure!

Reference a figure by its code chunk label with the fig: prefix, e.g., see Figure 3.1.

Inline 4

Table 3.1 and Table 3.2 using HTML custom cross-reference.

3 Dealing with and Displaying Dataframes

# install.packages('expss')
library(expss)
data(mtcars)
mtcars <-  apply_labels(mtcars,
                      mpg = "Miles/(US) gallon",
                      cyl = "Number of cylinders",
                      disp = "Displacement (cu.in.)",
                      hp = "Gross horsepower",
                      drat = "Rear axle ratio",
                      wt = "Weight (1000 lbs)",
                      qsec = "1/4 mile time",
                      vs = "Engine",
                      vs = c("V-engine" = 0,
                             "Straight engine" = 1),
                      am = "Transmission",
                      am = c("Automatic" = 0,
                             "Manual"=1),
                      gear = "Number of forward gears",
                      carb = "Number of carburetors")

Style standard - Tables Captions always above and Figures Captions always below.

Table 3.1: My caption
head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

3.1 Section

## Avoid displaying progress bar of the command
# This command is better than expss::info(mtcars)
library(sjPlot)
## Install package "strengejacke" from GitHub (`devtools::install_github("strengejacke/strengejacke")`) to load all sj-packages at once!
view_df <- sjPlot::view_df(mtcars)
## The command was separated in to 2 chunks in order to avoid outputting the progress bar to HTML
view_df
Data frame: mtcars
ID Name Label Values Value Labels
1 mpg Miles/(US) gallon range: 10.4-33.9
2 cyl Number of cylinders range: 4-8
3 disp Displacement (cu.in.) range: 71.1-472.0
4 hp Gross horsepower range: 52-335
5 drat Rear axle ratio range: 2.8-4.9
6 wt Weight (1000 lbs) range: 1.5-5.4
7 qsec 1/4 mile time range: 14.5-22.9
8 vs Engine 0
1
V-engine
Straight engine
9 am Transmission 0
1
Automatic
Manual
10 gear Number of forward gears range: 3-5
11 carb Number of carburetors range: 1-8

3.1.1 Very long subsection ————————————————————————–

library(DT)
library(labelled)
## 
## Attaching package: 'labelled'
## The following object is masked from 'package:expss':
## 
##     is.labelled
library(tidyverse)
## -- Attaching packages ------------------------------------------------ tidyverse 1.2.1 --
## v ggplot2 3.2.1     v purrr   0.3.3
## v tibble  2.1.3     v dplyr   0.8.3
## v tidyr   1.0.0     v stringr 1.4.0
## v readr   1.3.1     v forcats 0.4.0
## -- Conflicts --------------------------------------------------- tidyverse_conflicts() --
## x dplyr::between()   masks expss::between()
## x dplyr::compute()   masks expss::compute()
## x dplyr::contains()  masks tidyr::contains(), expss::contains()
## x dplyr::filter()    masks stats::filter()
## x dplyr::first()     masks expss::first()
## x stringr::fixed()   masks expss::fixed()
## x purrr::keep()      masks expss::keep()
## x dplyr::lag()       masks stats::lag()
## x dplyr::last()      masks expss::last()
## x purrr::modify()    masks expss::modify()
## x purrr::modify_if() masks expss::modify_if()
## x dplyr::na_if()     masks expss::na_if()
## x tidyr::nest()      masks expss::nest()
## x dplyr::recode()    masks expss::recode()
## x stringr::regex()   masks expss::regex()
## x purrr::transpose() masks expss::transpose()
## x dplyr::vars()      masks ggplot2::vars(), expss::vars()
DT::datatable(mtcars,
         extensions = c('FixedColumns',"FixedHeader",'Buttons'),
         rownames=TRUE,
         colnames=paste0(names(mtcars),": \n",  labelled::var_label(mtcars) %>% unlist() %>% as.character()),
         caption="My Table Title",
  editable=TRUE,
  # width=700, height=600,
          options = list(scrollX = TRUE,
                         paging=TRUE,
                         fixedHeader=TRUE,
                         fixedColumns=TRUE,
                         pageLength = 7,
                         dom = 'Bfrtip', buttons = c('copy', 'csv', 'excel', 'pdf', 'print')))
Table 3.2: My caption Table 3.3: My caption

3.2 Interactive Plots

3.2.1 Scatter 3D + Lines

#
library(plotly)
## Warning: package 'plotly' was built under R version 3.6.2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
##
p <- plotly::plot_ly(type = "scatter3d" ,
         x = c( 9, 8, 5, 1 ) ,
         y = c( 1, 2, 4, 8 ) ,
         z = c( 11, 8, 15, 3 ) ,
         mode = "lines+markers") ; p

3.2.2 Multiple Lines Graph with “Plotly HoverInfo / Hover text”

library(quantmod)
## Warning: package 'quantmod' was built under R version 3.6.2
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Registered S3 method overwritten by 'xts':
##   method     from
##   as.zoo.xts zoo
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## The following objects are masked from 'package:expss':
## 
##     first, last
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 3.6.2
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Version 0.4-0 included new data defaults. See ?getSymbols.
quantmod::getSymbols(Symbols = c("AAPL", "MSFT"))
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
## [1] "AAPL" "MSFT"
#
ds <- data.frame(Date = zoo::index(AAPL), AAPL[,6], MSFT[,6])
#
library(plotly)
p <- plotly::plot_ly(ds, x = ~Date) %>%
  add_lines(y = ~AAPL.Adjusted, name = "Apple") %>%
  add_lines(y = ~MSFT.Adjusted, name = "Microsoft") %>%
  layout(
    title = "Stock Prices",
    xaxis = list(
      rangeselector = list(
        buttons = list(
          list(
            count = 3,
            label = "3 mo",
            step = "month",
            stepmode = "backward"),
          list(
            count = 6,
            label = "6 mo",
            step = "month",
            stepmode = "backward"),
          list(
            count = 1,
            label = "1 yr",
            step = "year",
            stepmode = "backward"),
          list(
            count = 1,
            label = "YTD",
            step = "year",
            stepmode = "todate"),
          list(step = "all"))),
      rangeslider = list(type = "date")),
    yaxis = list(title = "Price"))  # ; p
##
## It does not work if the file type extension is inserted
# knitr::include_graphics(paste0(mypath,c("myplotly.png")))
## Also, it apparently only works with .png files
##_ And knitr::include_graphics generates an ERROR when rendering in HTML
library(knitr)
if(knitr::is_html_output() == FALSE){
  #
  knitr::include_graphics("myplotly2")
} else{
  print(p)
  p
}

Figure 3.1: Stocks figure caption

3.2.3 Static plots

# cars plot test1
plot(cars)

References