R/time_summary.R

#' Time summary
#'
#' Produce summaries time parameter in a command line style.
#'
#' @param list a list containing the different time series
#' @param graph logical, if TRUE graphic is plotted. If FALSE it is not.
#' @return an object of class time.summary wich indicates
#' \item{Steptime}{Steptime of measurement}
#' \item{First}{First measurement registered}
#' \item{Last}{Last measurement registered}
#' \item{Period}{Period covered by the different time series}
#'
#' @import ggplot2
#'
#' @author Remy Moine <remymoine95@gmail.com>
#' @export

time_summary<-function(list,graph){

  nb.TS<-length(list)

  Steptime<-NA
  First<-NA
  Last<-NA
  Period<-NA
  N.Data<-NA
  objet<-NULL

  for (i in c(1:length(list))){
    sttmp<-lubridate::as.duration(lubridate::int_diff(list[[i]]))
    tmp2<-as.character(lubridate::duration(unique(sttmp),units="second"))
    N.Data<-length(list[[i]])

    if(length(tmp2)!=1){stop(paste("There is more than one single steptime for time serie number",i,sep=""))} else {
      Steptime<-tmp2
      First<-as.character(list[[i]][1])
      Last<-as.character(list[[i]][length(list[[i]])])
      Period<-lubridate::as.duration(lubridate::int_diff(c(First,Last)))
    }

  Period<-as.character(lubridate::duration(as.numeric(Period),units="second"))

  tmpobjet<-list(Steptime=Steptime,First=First,Last=Last,Period=Period,N.Data=N.Data)
  objet<-rbind(objet,tmpobjet)}
  rownames(objet)<-names(list)

  class(objet)<-"time.summary"

  toto<-NULL
  TS<-NULL
  date<-NULL
  for (i in c(1:length(list))){
    tmp<-data.frame(date=list[[i]],TS=rep(names(list)[i]))
    toto<-rbind(toto,tmp)
  }

  p1<-ggplot2::ggplot(toto,aes(date,TS,col=TS))
  p2<-p1+ggplot2::geom_point(size=0.5,shape=15)
  p3<-p2+ggplot2::scale_x_datetime(date_breaks="1 month")
  p4<-p3+ggplot2::scale_y_discrete(breaks=unique(toto$TS))
  p5<-p4+ggplot2::labs(title="Extent of Time Series",x="Dates (monthly)",y="Time series' names")
  p6<-p5+ggplot2::scale_color_brewer(palette="Set1")
  p7<-p6+ggplot2::guides(col="none")
  p8<-p7+ggplot2::theme(axis.text.x = element_text(angle=45,hjust=1),
          axis.text.y = element_text(face="bold"),
          panel.background = element_rect(fill="white"),
          panel.grid.major.x = element_line(color="grey"),
          panel.grid.major.y = element_line(color="grey"))


  if(graph==T){p8}else{objet}
}
remymoine/PTS-R-package documentation built on May 16, 2019, 5:03 a.m.