使用 dygraph for R 仅按年份绘制 xts 时间序列? [英] Use dygraph for R to plot xts time series by year only?
问题描述
我正在尝试使用 R 库的新 dygraphs 来绘制每年波士顿马拉松比赛中男女获胜的时间.我有一个以秒为单位的获胜时间数据框,这是其中的一部分:
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))
但我不知道如何从中创建一个 xts 对象.我可以从每一列创建一个规则的时间序列,并在单独的图表中使用 dygraph 绘制每一个图表
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)
如果我尝试 cbind 时间序列,它将无法在 dygraph 中工作
If I try to cbind the time series it won't work in dygraph
both <- cbind(men, women)
dygraph(both)
错误信息是
xts(x.mat, order.by = order.by, frequency = frequency(x), ...) 中的错误:NROW(x) 必须匹配 length(order.by)
Error in xts(x.mat, order.by = order.by, frequency = frequency(x), ...) : NROW(x) must match length(order.by)
有什么建议吗?谢谢
推荐答案
这看起来像是 as.xts.ts
中的一个错误.它使用 length(x)
为索引创建日期序列,它返回矩阵的元素数(而不是行数).
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).
您可以通过在 ts 对象上使用 as.xts
来解决它,然后再对它们调用 cbind
.
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))
这篇关于使用 dygraph for R 仅按年份绘制 xts 时间序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!