2016-05-18 60 views
0

我对可能是一个非常简单的问题表示歉意,但我一直未能找到一个例子来解决它。我将简单的CSV数据提供给dygraphs,其中行包含不同的时间,然后为多个变量(当时)赋值。我可以将数据绘制得很好。但是,我想知道如何让dygraphs执行这些数据的功能。起初,我只是想计算各种变量的时间步长之间的差异,但之后我想做一些额外的事情,如计算平均值和标准偏差。我假设我需要在JavaScript代码中进行数学运算,但不知道如何去做。Dygraphs中时间序列的差异

所以,如果有人可以提供一个简单的例子来说明如何计算变量的时间步长之间的差异并获得dygraphs来绘制我真的很感激它。这就是我的意思...

如果这是提供的数据。

1:日期时间,VAR1,VAR2 2:日期时间,VAR1,VAR2 3:日期时间,VAR1,VAR2 ....

在每个日期时间,我想找到VAR1的值在前一个DateTime处为-var1,在前一个DateTime处为var2-var2,并绘制它们。

回答

0

这应该工作。由于您没有提供我创建的数据集。代码中的注释应解释每个步骤的作用。随意在评论中发布问题。运行时

df <- data.frame(time=c("2016-05-03","2016-05-04","2016-05-05"),start=c(5,4,2),end=c(2,6,3)) 
library(dplyr) 
#get dataframe with each row minus the previous row 
df<-mutate(df, diff.end= end-lag(end),diff.start= start-lag(start)) 
#convert the date string to a date object 
dates<-format(as.Date(df$time),format="%Y-%m-%d") 
#create dataframe with just the data we want to plot 
df<-cbind(df$diff.start,df$diff.end) 
colnames(df)<-c("starting.diff","ending.diff") 
#make the dataframe a time series object 
timeseriesobj<-xts(df,order.by=as.Date(dates)) 
timeseriesobj 
#create the dygraph 
dygraph(timeseriesobj) 
#note that the first point doesnt get plotted because its starting and ending values are NA 

代码输出:

> df <- data.frame(time=c("2016-05-03","2016-05-04","2016-05-05"),start=c(5,4,2),end=c(2,6,3)) 
> library(dplyr) 
> #get dataframe with each row minus the previous row 
> df<-mutate(df, diff.end= end-lag(end),diff.start= start-lag(start)) 
> #convert the date string to a date object 
> dates<-format(as.Date(df$time),format="%Y-%m-%d") 
> #create dataframe with just the data we want to plot 
> df<-cbind(df$diff.start,df$diff.end) 
> colnames(df)<-c("starting.diff","ending.diff") 
> #make the dataframe a time series object 
> timeseriesobj<-xts(df,order.by=as.Date(dates)) 
> timeseriesobj 
      starting.diff ending.diff 
2016-05-03   NA   NA 
2016-05-04   -1   4 
2016-05-05   -2   -3 
> #create the dygraph 
> dygraph(timeseriesobj) 
> #note that the first point doesnt get plotted because its starting and ending values are NA