Demo_Manuscript/2_Assemble_Daily_Summaries.R

# Setup -------------------------------------------------------------------

  rm(list = ls()) # Clear memory
  library(magrittr) # Attach magrittr package (makes code more readable)
  devtools::load_all() # Load functions etc. from the FLASh package

  ## Identify the files to process

    merged_files <- list.files(
      "Demo_Manuscript/_merged_data/60s/",
      full.names = TRUE
    )

# Summarizing function ----------------------------------------------------

  summarizer <- function(x) {

    timer <- PAutilities::manage_procedure(
      "Start", "\nProcessing", basename(x)
    )

    x %<>% readRDS(.)

    x%<>%
      names(.) %>%
      .[grepl("nonwear", ., TRUE)] %>%
      x[ ,.] %>%
      apply(1, any) %>%
      {x[!., ]} %T>%
      {if (nrow(.) != 1440) message(
        "\nRemoving ", 1440-nrow(.), " minute(s) with",
        " non-wear for one or more method(s)"
      )}

    sums <- c("id", "weightkg", "Date", "AG_Axis1", "AG_Axis2",
      "AG_Axis3", "AG_Steps", "AG_is_nonwear", "AG_kcal",
      "act24_is_nonwear", "act24_kcal", "swa_is_nonwear", "swa_kcal"
    )

    x %>%
    {.[ ,c("id", "weightkg", "Date", "AG_Axis1", "AG_Axis2",
      "AG_Axis3", "AG_Steps", "AG_kcal",  "act24_kcal", "swa_kcal"
    )]} %>%
    dplyr::group_by(
      ., id, weightkg, Date, n_minutes = nrow(.)
    ) %>%
    dplyr::summarise_all("sum") %>%
    data.frame(stringsAsFactors = FALSE) %T>%
    {PAutilities::manage_procedure("End", timer = timer)}

  }

# Apply the function to all files, then save the result -------------------

  lapply(merged_files, summarizer) %>%
  c(make.row.names = FALSE) %>%
  do.call(rbind, .) %>%
  {.[.$n_minutes >= 900, ]} %T>%
  {message(
    "Removing ", length(merged_files) - nrow(.),
    " participants with < 15 h of data"
  )} %>%
  saveRDS("Demo_Manuscript/_merged_data/day_level_summaries.rds") %>%
  invisible()
PAHPLabResearch/FLASH documentation built on May 15, 2020, 7:08 p.m.