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

Plotting data with varying time-averaging periods


In this recipe, we will learn how we can plot the same time series data by averaging it over different time periods using the aggregate() function.

Getting ready

We will only use the basic R functions for this recipe. Make sure that you load the openair.csv dataset.

air<-read.csv("openair.csv")

How to do it...

Let's plot the air pollution time series with weekly and daily averages instead of hourly values:

air$date = as.POSIXct(strptime(air$date, format = "%d/%m/%Y %H:%M", "GMT"))
means <- aggregate(air["nox"], format(air["date"],"%Y-%U"),mean, na.rm = TRUE)
means$date <- seq(air$date[1], air$date[nrow(air)],length = nrow(means))
plot(means$date, means$nox, type = "l")
means <- aggregate(air["nox"], format(air["date"],"%Y-%j"),mean, na.rm = TRUE)
means$date <- seq(air$date[1], air$date[nrow(air)],length = nrow(means))
plot(means$date, means$nox, type = "l",
xlab="Time", ylab="Concentration (ppb)",
main="Daily  Average Concentrations...