Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Formatting time series data for plotting


Time series or trend charts are the most common form of line graphs. There are a lot of ways in R to plot such data. However, it is important to first format the data in a suitable format that R can understand. In this recipe, we will look at some ways of formatting time series data using the base and some additional packages.

Getting ready

In addition to the basic R functions, we will also be using the zoo package in this recipe. So, first we need to install it:

install.packages("zoo")

How to do it...

Let's use the dailysales.csv example dataset and format its date column:

sales<-read.csv("dailysales.csv")

d1<-as.Date(sales$date,"%d/%m/%y")

d2<-strptime(sales$date,"%d/%m/%y")

data.class(d1)
[1] "Date"

data.class(d2)
[1] "POSIXt"

How it works...

We have seen two different functions to convert a character vector into dates. If we did not convert the date column, R will not automatically recognize the values in the column as dates. Instead, the...