R/freadCSV.R

Defines functions freadCSV

Documented in freadCSV

#' Function to Load a CSV data file into a proto Model structure
#' 
#' This function attempts to read a CSV data file of Observed data format into
#' a xts object. It uses read.csv and fails if the data does not have a uniform time step
#' 
#' @param filePath Full path to the csv file
#' @param ... Other paraemters to be passed to read.csv
#' 
#' @keywords FloorForT
#' @export
#' @examples
#' # Not Run
#' # ModelBuild()
freadCSV <- function(filePath,...){
    ## read in data
    tmp <- read.csv(filePath,...)
  
    ## process to give DateTime from input columns
    nms <- names(tmp)
    lwrnms <- tolower(nms)
    
    timeVars <- c('year','month','day','hour','minute','second')
    idx <- lwrnms %in% timeVars
    
    if( sum(idx)!=6 | !all(timeVars %in% lwrnms) ){
        stop("Misspecified time variables")
    }

    if( length(nms) < 8 ){
        stop("Not enough data series")
    }

    nms[idx] <- lwrnms[idx]
    names(tmp) <- nms
    
    ## make time series
    tmp[,"DateTime"] <- ISOdatetime(tmp$year, tmp$month, tmp$day,
                                    tmp$hour, tmp$minute, tmp$second,
                                    tz = "GMT")
    ens <- nms[!(nms %in% timeVars)]
    tmp <- tmp[,c("DateTime",ens)]
    
    ##   nms <- names(tmp)
    ##   if( !('DateTime' %in% nms) ){
    ##     stop("Missing time variables")
    ## }
    ## if( length(nms) < 3 ){
    ##     stop("Not enough data series")
    ## }
    
    ##   tmp[,"DateTime"] <- as.POSIXct(tmp[,'DateTime'],tz='GMT')
  
    ## ens <- setdiff(names(tmp),'DateTime') #timeVars)
    ## tmp <- tmp[,c('DateTime',ens)]
  
    ## Order by DateTime - required for later code since this is not checked again
    tmp <- tmp[order(tmp[,'DateTime']), ]

    ## check unique time step
    n <- nrow(tmp)
    udt <- unique(tmp[-1,"DateTime"]-tmp[-n,"DateTime"]) # unique converts from POSIXct
    if(length(udt)!=1){
        stop("Time steps are not constant")
    }
    
    ## make into xts object
    out <- xts(x = tmp[,ens],
               order.by = tmp[,'DateTime'],
               frequency = NULL,
               unique = TRUE,
               tzone = 'GMT')

    return(out)
  #return(tmp)
}
waternumbers/FloodForT documentation built on Nov. 5, 2019, 12:07 p.m.