R/ah_data_select.r

#' @title "ah_data_select" - Selects requested Apple Health information from the extracted data frame
#'
#' @description Selects requested Apple Health information from the extracted data frame
#'
#' @author Deepankar Datta <deepankardatta@nhs.net>
#'
#' @importFrom magrittr "%>%"
#' @importFrom rlang .data
#'
#' @param health_data A data frame containing extracted health data, in a format generated by the ah_import_xml.r function
#' @param type_filter Parameter to select the element "type" of health data to extract. Named so as the XML file groups elements by "type". See your data frame to see what types are available.
#' @param year_filter Optional parameter to select a specific year of data
#'
#' @return type_data A data frame containing the selected type elements
#'
#' @examples
#' # health_data <- ah_import_xml("export.xml")
#' # type_filter <- "BodyMassIndex"
#' # ah_data_select( health_data , type_filter )
#' # bmi_data <-ah_data_select( health_data , type_filter )
#'
#' @note Common types to pass to type_filter include:
#' @note BodyMassIndex
#' @note BodyMass
#' @note Height
#' @note HeartRate
#' @note DistanceWalkingRunning
#' @note StepCount
#'
#' @export

ah_data_select <- function( health_data , type_filter = NULL , year_filter = NULL ) {

  if( is.null(type_filter) && is.null(year_filter) ) {
    stop("You need to select one filter for this function to be useful.")
  }

  if( is.null(type_filter) == FALSE && is.null(year_filter) ) {
    type_data <- health_data %>%
      dplyr::filter( .data$type == type_filter ) %>%
      dplyr::group_by(.data$date, .data$month, .data$year)
  }

  if( is.null(type_filter) && is.null(year_filter) == FALSE ) {
    type_data <- health_data %>%
      dplyr::filter( .data$year == year_filter ) %>%
      dplyr::group_by(.data$date, .data$month, .data$year)
  }

  if( is.null(type_filter) == FALSE && is.null(year_filter) == FALSE ) {
    type_data <- health_data %>%
      dplyr::filter( .data$type == type_filter ) %>%
      dplyr::filter( .data$year == year_filter ) %>%
      dplyr::group_by(.data$date, .data$month, .data$year)
  }

  return( type_data )

  ## END OF FUNCTION

}
deepankardatta/AppleHealthAnalysis documentation built on May 28, 2019, 7:53 p.m.