

    # Sample Data 
    # ------------
      set.seed(1)
      # slightly different sizes for each group
      N1 <- 5e3
      N2 <- N1 + as.integer(rnorm(1, 0, 100))

      # One group has only a moderate amount of NA's
      SAMP1 <- rnorm(N1)
      SAMP1[sample(N1, .25 * N1, FALSE)] <- NA  # add in NA's

      # Another group has many NA's
      SAMP2 <- rnorm(N2)
      SAMP2[sample(N2, .95 * N2, FALSE)] <- NA  # add in large number of NA's

      # put them all in a list
      SAMP.NEW <- list(SAMP1, SAMP2)

      # keep it clean
      rm(SAMP1, SAMP2)

    # Execute 
    # -------    
      lapply(SAMP.NEW, meanIfThresh)




  meanIfThresh1 <- function(vec, thresh=12/15, len) { 
   # Calculates the mean of vec, however, 
   #   if the number of non-NA values of vec is less than thresh, returns NA 
  
  # thresh : represents how much data must be PRSENT. 
  #          ie, if thresh is 80%, then there must be at least 

    # for efficiency, allow len to be an argument. If not set, compute it. 
    if (missing(len))
      len <- length(vec)

    # if the proportion of NA's is greater than the threshold, return NA
    if( (sum(is.na(vec)) / len) > thresh)
      return(NA_real_)
    # example:  if I'm looking at 14 days, and I have 12 NA's,
    #            my proportion is 85.7 % = (12 / 14)
    #           default thesh is  80.0 % = (12 / 15)
    #          Thus, 12 NAs out of 14 would be rejected
    

    # else
    return(mean(vec, na.rm=TRUE))       
  }


meanIfThresh2 <- function(vec, thresh=12/15) { 

  len <- length(vec)
  nas <- is.na(vec)
  Nna <- sum(nas)
  if( (Nna / len) > thresh)
    return(NA_real_)

  return(sum(vec[!nas])/(len-Nna))
}

M1=quote(lapply(SAMP.NEW, meanIfThresh1))
M2=quote(lapply(SAMP.NEW, meanIfThresh2))

mbench(M1, M2)

m1 <- lapply(SAMP.NEW, meanIfThresh1)
m2 <- lapply(SAMP.NEW, meanIfThresh2)
identical(m1, m2)

m1[[1]] - m2[[1]]
