Here are some libraries we will be using.

library(reshape2)  #melt and cast
library(tidyverse)  #ggplot2 and dplyr
library(readr)  #read in URLs
library(formatR)
library(corrplot)  #correlation matrices and correlograms
library(tibble)  #clean little tibbles
library(RColorBrewer)  #creates custom color palettes
library(splitstackshape)  #generates ID variables, crazy useful little tool.
library(ggdendro)  #dendrograms
library(TTR)  #smoothing and simple moving averages for time series
library(readxl)

1 Lagging a sequence of numbers

Generate fake data; rename the column header

set.seed(123)
a <- as.data.frame(sample(1:100, 30))
colnames(a) <- "a"
head(a)
##    a
## 1 29
## 2 79
## 3 41
## 4 86
## 5 91
## 6  5

1.1 Lag the data

Lag the previous sequence by 1, append to dataframe

b <- as.data.frame(lag(a$a, 1))
colnames(b) <- "b"
c <- data.frame(a, b)
head(c, n = 5)
##    a  b
## 1 29 NA
## 2 79 29
## 3 41 79
## 4 86 41
## 5 91 86

1.2 Subtract the previous observation from each new observation

This creates a new “difference” variable which reflects each observation minus the previous observation

d <- c %>% mutate(difference.column = c$a - lag(c$a, 1))  #default is to lag by 1
head(d, n = 10)
##     a  b difference.column
## 1  29 NA                NA
## 2  79 29                50
## 3  41 79               -38
## 4  86 41                45
## 5  91 86                 5
## 6   5 91               -86
## 7  50  5                45
## 8  83 50                33
## 9  51 83               -32
## 10 42 51                -9