R/matlab.R

#' Reads the .mat structured time series data output generated by 'Matlab' and
#' creates an xts-object.
#'
#' @title Read time series data from .mat file format
#' @param file The file to be read.
#' @param data_cols Specifies the columns the data is stored.
#' @param time_col Specifies the column the time is stored.
#' @return An xts-object.
#' @rdname read_mat
#' @export 
#' @seealso \code{\link[xts]{xts}}.
read_mat <- function(file, data_cols = 2, time_col = 1) {
  
  warning("Implementation still under development. Please check the conversion!")
  
  if (!requireNamespace("R.matlab", quietly = TRUE)) {
    stop("R.matlab needed for this function to work. Please install it.",
         call. = FALSE)
  }

  # read file
  raw <- R.matlab::readMat(file)
  
  # extract relevant data and transpose it
  data <- t(raw[[1]])
  
  # important: Convert between MATLAB datenum values and R POSIXct time values.
  time <- as.POSIXct( (data[,time_col] - 719529)*86400, 
                      tz = "GMT",
                      origin = "1970-1-1")
  
  # create xts object
  ts <- xts::xts(x = data[,data_cols], order.by = time)
  
  invisible(ts)
  
}
dleutnant/tsconvert documentation built on May 15, 2019, 9:17 a.m.