R/swa_utils.R

Defines functions swa_get_time swa_check_variables swa_read

Documented in swa_check_variables swa_get_time swa_read

#' Read a data sheet from a SenseWear Armband Excel file
#'
#' @param file character. Path to the file
#' @param sheet_name character. Name of the sheet
#'
#' @keywords internal
swa_read <- function(file, sheet_name) {

  swa <- try(
    readxl::read_excel(file, sheet = sheet_name)
  )

  if ("try-error" %in% class(swa)) {
    cat(
      "\n\n", basename(file),
      "is formatted incorrectly on the",
      sheet_name, "sheet. Setting to NULL."
    )
    return(NULL)
  }

  swa %>%
  data.frame(stringsAsFactors = FALSE)

}

#' Do format checking on SenseWear Armband data
#'
#' @inheritParams swa_get_time
#'
#' @keywords internal
swa_check_variables <- function(swa) {

  {if ("Timestamps" %in% names(swa)) {
    warning(
      "`Timestamps` column needs to be deleted for ",
      swa$id[1],
      call. = FALSE
    )
    return(NULL)
  }}

  if (!any(grepl("METs", names(swa)))) {
    warning(
      "No MET values for ", swa$id[1], call. = FALSE
    )
    return(NULL)
  }

  swa

}

#' Fetch, check, and format the armband timestamp data column
#'
#' @param swa data frame input containing armband data
#'
#' @keywords internal
swa_get_time <- function(swa) {

  time_index <-
    names(swa) %>%
    grepl("time", ., TRUE) %>%
    which(.) %T>%
    {stopifnot(length(.) == 1)}

  swa[ ,time_index] %>%
  class(.) %>%
  grepl("^POSIX", .) %>%
  any(.) %>%
  stopifnot(.)

  swa[ ,time_index] %>%
  attr("tz") %>%
  {stopifnot(. == "UTC")}

  names(swa)[time_index] <- "Time"

  swa

}

#' Fetch, check, and format the armband intensity data column
#'
#' @inheritParams swa_get_time
#' @keywords internal
swa_get_intensity <- function(swa) {

  met_index <-
    names(swa) %>%
    grepl("METs", ., TRUE) %>%
    which(.) %T>%
    {stopifnot(length(.) == 1)}

  new_names <-
    names(swa) %>%
    append("Intensity", met_index)

  swa$Intensity <-
    swa[ ,met_index] %>%
    PAutilities::get_intensity(
      breaks = c(-Inf, 1.51, 3, 6, Inf),
      labels = c("SB", "LPA", "MPA", "VPA")
    )

  swa[ ,new_names]

}
PAHPLabResearch/FLASH documentation built on May 15, 2020, 7:08 p.m.