R/plotruns.R

Defines functions plotruns

Documented in plotruns

#' Produces longitudinal plots of the cgms data for each subject in a cgms.df dataframe
#' to the mean glucose value of a cgms.df dataframe
#'
#' @param df input cgms.df dataframe
#' @param outputdir folder to save in
#' @param name what to call the file
#' @keywords null distributions
#' @export
#' @examples plotruns(cgms.df,outputdir,name)
#Plot time course data for each subject, save to figures folder as df.plotruns
plotruns <- function(df,outputdir,name) {

  ###Make a plot for each subject ID, then assign it to a global variable
  lapply(
    unique(df$subj_id),
    FUN = function(SUBJ) {
      df_filtered <- df %>%
        dplyr::filter(subj_id == SUBJ)
      plot <- ggplot2::ggplot(df_filtered,
                     aes(x = time_past_start,
                         y = historic_glucose,
                         color = run_id)
      ) +
        ggplot2::geom_point() +
        ggplot2::coord_cartesian(ylim = c(min(df$historic_glucose),
                                 max(df$historic_glucose)),
                        xlim = c(0,
                                 as.numeric(max(df$time_past_start))
                        ),
                        expand = F
        ) +
        ggplot2::scale_x_continuous(labels = seq(0,12,1),
                           breaks = seq(0,12,1)) +
        ggplot2::labs(x = 'Days since start', y = "Blood Glucose mg/dL")
      assign(paste(obj2str(df),
                   SUBJ,
                   sep = "."),
             plot,
             envir = .GlobalEnv)
    }
  )

  #plot all tables as a big pdf and save
  plotlist <- mget(paste(obj2str(df),
                         unique(df$subj_id),
                         sep = "."),
                   envir = .GlobalEnv)

  allruns <- gridExtra::marrangeGrob(plotlist, nrow = 3, ncol = 1)

  ggplot2::ggsave(paste(name,
               "plotruns.pdf",
               sep = "_"),
         allruns,
         path = outputdir,
         width = 11,
         height = 8)

  #clean environment
  assign("plotlist",
         plotlist,
         envir = .GlobalEnv)
  remove(list = c(names(plotlist),"plotlist"), envir = .GlobalEnv)

}
hamsamilton/cgms.analysis documentation built on March 29, 2020, 12:57 a.m.