R/CalcEnSlideDist.R

Defines functions CalcEnSlideDist

Documented in CalcEnSlideDist

#' Calculates Sliding Entropy for groups of interest in dataframes. Instead of returning a mean, return the value for all windows.
#' @author Samuel Hamilton
#' @param df input cgms.df dataframe
#' @param entmeasure chosen entropy measure. Either FastSampEn or FastApEn. String
#' @param ofint variable of interest to calculate entropy on from the datagrame. String
#' @param varlist Which groups to separate dataframe by
#' @param r_thrsh what is the tolerance value r. This is multiplied by the sd of the whole ofint column.
#' @param size the window size
#' @param step step length
#' @import TSEntropies dplyr ggplot2
#' @keywords null distributions
#' @return dataframe with the entropy value for each group in varslist
#' @export
#' @examples CalcEnSlide(df = cgms.df,varlist = c("Group"))
CalcEnSlideDist <-  function(entmeasure = "FastSampEn",df,varlist,r_thrsh = .2,size = 200,N = 200) {

  #Define entropy function
  calcen <- function(entmeasure,ofint,size,r_thresh) {
    start <- sample(seq(from = 1, to = (length(ofint) - size)), size = 1)
    end <- start + size
    window <- ofint[start:end]
    EN <- do.call(entmeasure,list(window, r = r_thresh*sd(window)))
    return(EN)
  }

  #initialize df

  df2 <- data.frame(matrix(ncol = length(varlist) + 1,nrow = 0))
  colnames(df2) <- append(varlist,"historic_glucose")
  for (i in 1:N){
    k <- plyr::ddply(df,
               varlist,
               summarise,
               entropy = calcen(entmeasure = entmeasure,
                                ofint = historic_glucose,
                                size = size,
                                r_thresh = r_thrsh)
    )
    df2 <- rbind(df2,k)
  }
  return(df2)
}
hamsamilton/cgms.analysis documentation built on March 29, 2020, 12:57 a.m.