I had two different methods of calculating whether a column was unique by group.
New Way much faster and very specific to data.table


isUniqueByGroup <- function(DT, colsToCheck=setdiff(names(DT), byCols), byCols=key(DT), verbose=TRUE, sampleThresh=5e3) {

  # ------------------------------------------- #
  #   Input Check                               # 
  # ------------------------------------------- #
  if (any(badVal <- colsToCheck %chin% byCols)) {
    if (all(badVal)) {
      warning("\nAll columns in `colsToCheck` are also in `byCols`. By definition, there will be only one row per group.")
      return(invisible(NULL))
    } else {
      warning(warningCols("The following column names are in *both* `colsToCheck` and `byCols` and\n  were dropped from colsToCheck (since they will, by definition, have one row per group)", colsToCheck[badVal]))
      colsToCheck <- colsToCheck[!badVal]
    }
  }

  if (any(badVal <- setdiff(c(colsToCheck, byCols), names(DT)))) {
    warning(warningCols("The following are *not* columns of the DT: " , badVal))
    colsToCheck <- intersect(colsToCheck, names(DT))
    byCols      <- intersect(byCols, names(DT))
  }
  if (!length(colsToCheck)) {
    stop("colsToCheck does not have a valid length, and might be NULL")
  }
  if (!length(byCols)) {
    stop("byCols does not have a valid length, and might be NULL")
  }

  # ------------------------------------------- #

  rows.expected <- nrow(DT[, .N, by=byCols])
  rows.actual   <- nrow(DT[, .N, by=c(byCols, colsToCheck)])

  ## IF THEY ARE THE SAME
  if (identical(rows.expected, rows.actual))
    return(TRUE)

  ## ELSE
  ret <- FALSE 
  
  attr(ret, "has.dups") <- 
      DT[, 1, by=c(byCols, colsToCheck)][, .N, by=byCols][N>1]

  return(ret)


  ## THIS WAS THE OLD METHOD.  
  ##  I am keeping it here for reference

  samp.inds <- TRUE
  if (length(sampleThresh) && !is.na(sampleThresh)) {
    samp.perc <- .3
    if (sampleThresh <  {.nrow.bygrp <- nrow(DT[, .GRP, by=byCols])} )
        samp.inds <- TF.sample(samp.perc, nrow(DT))
    if (verbose)
      cat("There are ", prettyNum(.nrow.bygrp, big.mark=",")," unique groups and ", prettyNum(nrow(DT), big.mark=",")," total rows.\nWe will sample", fwp(samp.perc, 0), "of the rows.\n")
  }

  results <- 
    DT[samp.inds, list(singleVal= {1==nrow(unique(.SD, by=colsToCheck))})
           , .SDcols=colsToCheck  # need .SDcols if (any(colsToCheck %in% byCols))
           , keyby=byCols][!(singleVal)
              , if (!(nrow(.SD)))
                  TRUE
                else
                  .SD[, byCols, with=FALSE]
              ]

}