Welcome to the hotseat. We've prepared a guide if you'd like to read more about how it works.

Plotting Time Series in R

0 votes
asked Apr 13, 2017 in STA 3041F - Time Series and Markov Chains by Pandy (2,850 points)

I'm trying to match a plot given in the lecture slides (see below). A sample of the data is given below:

Month Passengers
Jan-49 112
Feb-49 118
Mar-49 132
Apr-49 129

I'm not sure how to go about converting the months column into what's given in the slide. I've tried as.Date but that returns NA (I'm assuming because there's no day in the date). 



1 Answer

+1 vote
answered Apr 16, 2017 by Rowan (4,010 points)
selected Apr 17, 2017 by Pandy
Best answer

Hi Pandy

I have not tried this in R, but I will give you the info and then you can comment if you have any further questions. Looking at the manual page for 'as.date' found here. It seems that it will not be able to handle the date strings without a little coercion. There are three methods I would try.

First, try using the format parameter for the as.date function. This parameter accepts a string which specifies how the dates being handled are formatted. The symbols used for the formatting are described here. For your specific case I would try to use the string '%b-%y'. This should allow for the proper handling of the dates you have. However, there may be an issue as there is no date. This leads to the second method.

If there is a problem to there being no date, you could simply append each string with a '-01' (This can be done easily using vector assignment or a loop) and then use the format string '%b-%y-%d' with the as.date function.

Finally, if neither of the above works, then you will have to write your own function to convert the string dates from the data into a more normal string date format e.g. '01-05-1995' and then use the as.date function on the new strings. This is by far the method requiring the most effort, so I would only use it as a last resort.

If you have any further questions, please comment on this answer and I will be happy to help. I am also interested to know how it turns out, so please comment to let me know either way.


commented Apr 17, 2017 by Pandy (2,850 points)

Hi Rowan, thanks for your response.

I couldn't use your first suggestion as there was no 'day'. I landed up looping through the dates, adding a "-01" to the end, adding a "19" to the front of each year (otherwise R assumed 46 meant 2046, for example) and then formatting with as.Date.

Then, plotting the data worked perfectly! Thanks again.

commented Apr 17, 2017 by Rowan (4,010 points)

Cool, thanks for letting me know.