R/utils.R

#' Cleans HeavySet imported data.
#'
#' This functions will set the column names correctly, so your dataframe can be used by all the other functions.
#'
#' @param input The raw HeavySet dataframe.
#'
#' @return A dataframe of class data.frame & HS.data.frame
#'
#' @importFrom dplyr mutate
#'
#' @export
cleanHSinput <- function(input) {
  if (ncol(input) != 7) {
    stop("The number of columns for a HeavySet export dataframe should be 7")
  }
  colnames(input) <-
    c("date",
      "workoutName",
      "exerciseName",
      "reps",
      "weightKg",
      "weightLb",
      "notes")

  if (!is.factor(input$workoutName)) {
    input$workoutName <- as.factor(input$workoutName)
  }
  if (!is.factor(input$exerciseName)) {
    input$exerciseName <- as.factor(input$exerciseName)
  }
  if (!is.factor(input$notes)) {
    input$notes <- as.factor(input$notes)
  }
  if (!inherits(input$date, "Date")) {
    input <- dplyr::mutate(input, date = as.Date(date))
  }
  return(input)
}


#' Appends HeavySet dataframe class.
#'
#' This functions will append the class `HS.data.frame` to an object of class `data.frame`.
#'
#' @param df a data.frame
#'
#' @return A dataframe of class data.frame & HS.data.frame
addHSclass <- function(df) {
  class(df) <- append(class(df), "HS.data.frame")
  return(df)
}

#' Check a dataframe for the `HS.data.frame`.
#'
#' This functions will check if a data.frame is from class `data.frame` and `HS.data.frame`
#'
#' @param df A dataframe
#'
checkHSclass <- function(df) {
  if (class(df)[1] == "data.frame") {
    if (is.null(class(df)[2])) {
      message("HS.data.frame is added as a class to your object.")
      df <- addHSclass(df)
      return(df)
    } else if (class(df)[2] == "HS.data.frame") {
      stop("HS.data.frame is already a class for your object.")
    }
  } else {
    stop("Your initial input should be of class data.frame")
  }
}

# tryCatch(
#   stopifnot(class(df)[1] != "data.frame"),
#   error = function()
#     stop("The input is not a data.frame")
# )
MarijnJABoer/HeavySetR documentation built on May 22, 2019, 5:31 p.m.