Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use dygraph for R to plot xts time series by year only?

Tags:

r

xts

I am trying to use the new dygraphs for R library to plot winning times for men and women in the Boston Marathon each year. I've got a data frame of winning times by second, here's a portion of it:

winners <- data.frame(year=1966:1971, mensec=c(8231, 8145, 8537, 8029, 7830, 8325), womensec=c(12100, 12437, 12600, 12166, 11107, 11310))

But I don't know how to create an xts object from this. I can create a regular time series from each column and graph each one using dygraph in a separate graph

men <- ts(winners$mensec, frequency = 1, start=winners$year[1])
dygraph(men)
women <- ts(winners$womensec, frequency = 1, start=winners$year[1])
dygraph(women)

If I try to cbind the time series it won't work in dygraph

both <- cbind(men, women)
dygraph(both)

The error message is

Error in xts(x.mat, order.by = order.by, frequency = frequency(x), ...) : NROW(x) must match length(order.by)

Any suggestions? Thanks

like image 406
Sharon Avatar asked Feb 03 '15 17:02

Sharon


1 Answers

This looks like a bug in as.xts.ts. It uses length(x) to create the sequence of dates for the index, which returns the number of elements for a matrix (not the number of rows).

You can work around it by using as.xts on your ts objects before calling cbind on them.

both <- cbind(men=as.xts(men), women=as.xts(women))
like image 91
Joshua Ulrich Avatar answered Oct 13 '22 11:10

Joshua Ulrich