R supports many useful manipulations with date objects such as date addition and subtraction, and the creation of date sequences. This recipe shows many of these operations in action. For details on creating and examining date objects, see the previous recipe Creating and examining date objects, in this chapter.
Getting ready
The base R package provides date functionality, and you do not need any preparatory steps.
How to do it...
Perform the addition and subtraction of days from date objects:
> dt <- as.Date("1/1/2001", format = "%m/%d/%Y")
> dt
[1] "2001-01-01"
> dt + 100 # Date 100 days from dt
[1] "2001-04-11"
> dt + 31
[1] "2001-02-01"
Subtract date objects to find the number of days between two dates:
Performing preliminary analyses on time series data
Before creating proper time series objects, we may want to do some preliminary analyses. This recipe shows you how.
Getting ready
The base R package provides all the necessary functionality. If you have not already downloaded the data files for this chapter, please do it now and ensure that they are located in your R working directory.
How to do it...
Read the file. We will use a data file that has the share prices of Walmart (downloaded from Yahoo Finance) between March 11, 1999 and January 15, 2015:
> wm <- read.csv("walmart.csv")
View the data as a line chart:
> plot(wm$Adj.Close, type = "l")
How to do it...
Compute and plot daily price movements:
> d <- diff(wm$Adj.Close)
> plot(d, type = "l")
The plotted daily price movements appear as follows:
How to do it...
Generate a histogram of the daily price changes, along with a density plot:
> hist(d, prob = TRUE, ylim = c(0,0.8), main = "Walmart stock", col = "blue")