6
votes

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

2

2 Answers

9
votes

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))
4
votes

Looks like Joshua answered the question. Here is the full answer with slightly different code and also with a year x-axis formatter.

library(xts)
library(dygraphs)

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

winners_xts <- as.xts(
  winners[-1]
  , order.by = as.Date(
    paste0(winners$year,"-01-01",format="%Y-01-01")
  )
)

dygraph( winners_xts ) %>%
  dyAxis( 
    name="x"
    ,axisLabelFormatter = "function(d){ return d.getFullYear() }"
  )

# using the original data here is a way to merge
#   merge will work just like cbind
#   but need to convert to xts first
men <- ts(winners$mensec, frequency = 1, start=winners$year[1])
women <- ts(winners$womensec, frequency = 1, start=winners$year[1])
do.call(merge,Map(as.xts,list(men=men,women=women)))