Beginning R date plots and analysis with Matrix object?
I want to plot the data as a time series (quarterly) but the plot keeps treating the dates as Data not labels or time?
Trying to keep my initial exercise very simple, (have more complex stuff to get on with, it would be a snap with Excel or even GDocs!) I am reading a very small table from csv (using read.csv) as
This is the display for Corl (my data in r)
Date Survey Actual
1 2011-06-30 60 NA
2 2011-03-31 55 50
3 2010-12-31 48 44
4 2010-09-30 48 36
5 2010-06-30 56 75
6 2010-03-31 57 41
I tried to convert to date using Corl$Date <- as.Date(Corl$Date) but no difference.
I have used both plot(Corl) and plot.ts(Corl)
I'll then want to run correlate and auto correlate but I seem to be missing a basic concept for the data structure?
I also tried inverting the columns and row开发者_如何转开发s,
V1 V2 V3 V4 V5 V6
1 Date 2010-03-31 2010-06-30 2010-09-30 2010-12-31 2011-03-31
2 Survey 57 56 48 48 55
3 Actual 41 75 36 44 50
V7
1 2011-06-30
2 60
3
dput(Corl)
structure(list(Date = structure(c(15155, 15064, 14974, 14882,
14790, 14699), class = "Date"), Survey = c(60L, 55L, 48L, 48L,
56L, 57L), Actual = c(NA, 50L, 44L, 36L, 75L, 41L)), .Names = c("Date",
"Survey", "Actual"), row.names = c(NA, -6L), class = "data.frame")
Plot as follows:
From the output of dput(Corl)
we don't have to guess at how the Date values are stored in Corl. As you can see below, the Dates are stored as class = "Date". That makes this fairly easy.
library(zoo)
Corl <- structure(list(Date = structure(c(15155, 15064, 14974, 14882,
14790, 14699), class = "Date"), Survey = c(60L, 55L, 48L, 48L,
56L, 57L), Actual = c(NA, 50L, 44L, 36L, 75L, 41L)), .Names = c("Date",
"Survey", "Actual"), row.names = c(NA, -6L), class = "data.frame")
Corl.zoo <- read.zoo(Corl, FUN=as.yearqtr)
Corl.zoo
Survey Actual
2010 Q1 57 41
2010 Q2 56 75
2010 Q3 48 36
2010 Q4 48 44
2011 Q1 55 50
2011 Q2 60 NA
plot(Corl.zoo)
Edit 1 ======================================================
Before you ask, here's a way to add vertical grid lines and more labels across the x axis. All I did was modify the example code at the bottom of the following link:
http://rss.acs.unt.edu/Rdoc/library/zoo/html/plot.zoo.html
my.panel <- function(...) {
lines(...)
#This line adds the vertical grid lines
abline(v=time(Corl.zoo), col="lightgray", lty=3)
panel.number <- parent.frame()$panel.number
# if bottom panel
if (!length(panel.number) || panel.number == NCOL(Corl.zoo)) {
# next line only if non-labelled ticks wanted for each point
axis(1, at = time(Corl.zoo), lab = FALSE)
labcou <- 1 #Put a label, counting between labels
ix <- seq(1, length(Corl.zoo), labcou)
labs <- format(time(Corl.zoo), "%Y\nQ%q\n ")
axis(1, at = time(Corl.zoo)[ix], lab = labs[ix], tcl = -0.5, padj=0.6, cex.axis = 1)
}
}
plot(Corl.zoo, panel = my.panel, xaxt = "n", main="My Title", xlab="")
精彩评论