R/load.R

Defines functions read_eprime

Documented in read_eprime

#' Read in a text file generated by Eprime
#'
#' @param filename Either the full or relative path to an Eprime .txt file
#' @param remove_clock Whether to exclude the Clock.Information XML entries.
#'   Enabled by default.
#' @return Each line of the file is stored and returned in a character vector.
#'
#' @details The encoding on an Eprime txt file should be UCS-2 Little Endian,
#'   but sometimes this is not the case. We delegate the fussy encoding details
#'   to the \code{stringi::str_read_lines} function.
#'
#'   If the file is not an Eprime txt--that is, if it is missing the lines
#'   \code{*** Header Start ***} and \code{*** Header End ***}--a warning is
#'   raised and the lines of text are replaced by a dummy header.
#' @export
read_eprime <- function(filename, remove_clock = TRUE) {
  basename <- tools::file_path_sans_ext(basename(filename))

  raw <- stringi::stri_read_raw(filename)
  top_enc <- stringi::stri_enc_detect(raw)[[1]][1, 1]
  eprime_log <- stringi::stri_read_lines(filename, encoding = top_enc)


  if (!has_header(eprime_log)) {
    warning(filename, " is not an Eprime txt file. Dummy text will be used instead.")
    eprime_log <- c("*** Header Start ***", "*** Header End ***")
  }


  if (remove_clock) {
    clock_lines <- str_detect(eprime_log, "Clock.Information: ")
    eprime_log <- eprime_log[!clock_lines]
  }

  attr(eprime_log, "basename") <- basename
  class(eprime_log) <- c("EprimeLines", "character")
  eprime_log
}
tjmahr/rprime documentation built on Sept. 30, 2020, 5:31 p.m.