Time series objects deserve a special mention as they can be useful for numerical data and allow the ability to forecast which can be useful for example when determining what the throughput in an outpatient clinic is likely to be so we can plan ahead.

Create a time series- numerical data

Dataframes can be formatted as time series objects as follows

#Sample dates
dat<-sample(seq(as.Date('2013/01/01'), as.Date('2017/05/01'), by="day"), 100)

rndm1<-sample(seq(0,40),100,replace=T)
rndm2<-sample(seq(0,40),100,replace=T)
rndm3<-sample(seq(0,40),100,replace=T)
df<-data.frame(dat,rndm1,rndm2,rndm3)


library(xts)
Myxts<-xts(df, order.by=df$dat)
kable(head(Myxts,25))
dat rndm1 rndm2 rndm3
2013-02-02 27 4 10
2013-02-06 1 9 31
2013-04-25 26 12 35
2013-05-05 30 39 3
2013-05-25 5 40 22
2013-06-16 35 15 0
2013-06-20 18 11 11
2013-07-08 13 20 24
2013-07-12 40 8 29
2013-07-26 31 13 22
2013-07-29 36 3 12
2013-08-14 4 16 29
2013-08-25 22 3 36
2013-09-04 38 8 35
2013-10-07 15 34 10
2014-01-14 24 10 32
2014-02-25 9 6 25
2014-03-10 9 9 34
2014-04-03 16 38 13
2014-04-14 31 35 27
2014-04-20 20 38 2
2014-05-14 4 7 0
2014-05-15 40 35 37
2014-05-26 29 9 2
2014-06-17 26 37 36
##Create a ti me serie s- mixed categorical and numerical data

but what if we have categorical data as well. In this case we have to use another package as follows

library(tidyquant)
library(ggplot2)
library(dplyr)

dat<-sample(seq(as.Date('2013/01/01'), as.Date('2017/05/01'), by="day"), 100)
proc<-sample(c("EMR","RFA","Biopsies"), 100, replace = TRUE)
rndm1<-sample(seq(0,40),100,replace=T)
df<-data.frame(dat,rndm1,rndm2,rndm3,proc)

#Get the table in order so the groups are correct:
df<-df%>%group_by(proc)

mean_tidyverse_downloads_w <- df %>%
    tq_transmute(
        select     = rndm1,
        mutate_fun = apply.weekly, 
        FUN        = mean,
        na.rm      = TRUE,
        col_rename = "mean_count"
    )

Plot the time series

    ggplot(mean_tidyverse_downloads_w,aes(x = dat, y = mean_count, color = proc)) +
    geom_point() +
    geom_smooth(method = "loess") + 
    labs(title = "Number of procedures per week", x = "", 
         y = "Number of procedures per week") +
    facet_wrap(~ proc, ncol = 3, scale = "free_y") +
    expand_limits(y = 0) + 
    scale_color_tq() +
    theme_tq() +
    theme(legend.position="none")

Predictions

Of course one of the best things about Time series analysis is the ability to forecast. We can use the aptly named forecast package to do this and an example can be seen here More detail about forecasting can be found here: http://a-little-book-of-r-for-time-series.readthedocs.io/en/latest/index.html including examples in R.