這應該工作。由於您沒有提供我創建的數據集。代碼中的註釋應解釋每個步驟的作用。隨意在評論中發佈問題。運行時
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