R/FemFit_mergeCSVs.r

#' Merge sessions in an FemFit dataset
#'
#' @description
#' Processes an FemFit dataset to merge sessions.
#'
#' @param x An "FemFit" object.
#' @param whichSession A character vector of session identifiers. Defaults to merging all sessions.
#'
#' @details
#' Merges all of the valid comma separated value file(s). The resulting session identifier is determined by alphabetical order.
#'
#' @seealso
#' \code{\link{read_FemFit}}
#'
#' @return
#' Returns the processed "FemFit" object.
#'
#' @examples
#' AS013 = read_FemFit(c(
#'         "Datasets_AukRepeat/dee8fc3fdcfccb27_640_csv.zip",
#'         "Datasets_AukRepeat/dee8fc3fdcfccb27_641_csv.zip"
#'     ))
#'
#' # Extract the unique sessionIDs
#' sessionIDs = unique(AS013$df$sessionID)
#'
#' print(sessionIDs)
#' # The output is: [1] "640 19:43" "641 20:04" "641 20:08"
#'
#' # More sensible to merge the latter two sessions together rather than the first two
#' AS013 = FemFit_mergeCSVs(AS013, sessionIDs[2:3])
#'
#' @export
FemFit_mergeCSVs = function (x, whichSession = "") {
  # Throw an error if the x argument is not an FemFit object or missing
  if (!inherits(x, "FemFit") || is.na(x)) {
    stop("The x argument is not an FemFit object.", call. = FALSE)
  }

  # Throw an error if the whichSession argument is not a character or missing
  if (any(!is.character(whichSession) || is.na(whichSession))) {
    stop("The provided whichSession argument is not a character.", call. = FALSE)
  }

  sessionIDs = x$df$sessionID %>% unique

  # Throw an error if the number of sessionIDs is equal to 1
  if (length(sessionIDs) == 1) {
    stop("The provided FemFit object only has one session in it.", call. = FALSE)
  }

  # Throw an error if the whichSession argument does not map to the sessionIDs
  if (!all(whichSession %in% sessionIDs) && whichSession != "") {
    stop("The provided whichSession argument specifies sessionIDs which do not exist in x$df.", call. = FALSE)
  }

  # Merge the selected sessionIDs
  x$df = x$df %>%
    dplyr::mutate(toMerge = sessionID %in% whichSession | all(whichSession == "")) %>%
    dplyr::group_by(toMerge) %>%
    dplyr::mutate(sessionID = dplyr::if_else(toMerge, unique(sessionID)[1], sessionID),
                  time = dplyr::if_else(toMerge, trunc(row_number()*10 - 10), time)) %>%
    dplyr::ungroup(toMerge) %>%
    dplyr::select(-toMerge)

  return (x)
}
TheGreatGospel/IVPSA documentation built on May 19, 2019, 1:47 a.m.