1
#' Count
2
#'
3
#' Count the numbers of observations within groups
4
#'
5
#' @param dt_ the data table to uncount
6
#' @param ... groups
7
#' @param na.rm should any rows with missingness be removed before the count? Default is \code{FALSE}.
8
#' @param wt the wt assigned to the counts (same number of rows as the data)
9
#'
10
#' @examples
11
#'
12
#' library(data.table)
13
#' dt <- data.table(
14
#'   x = rnorm(1e5),
15
#'   y = runif(1e5),
16
#'   grp = sample(1L:3L, 1e5, replace = TRUE),
17
#'   wt = runif(1e5, 1, 100)
18
#'   )
19
#'
20
#' dt_count(dt, grp)
21
#' dt_count(dt, grp, na.rm = TRUE)
22
#' dt_count(dt, grp, na.rm = TRUE, wt = wt)
23
#'
24
#' @import data.table
25
#' @importFrom stats complete.cases
26
#'
27
#' @export
28
dt_count <- function(dt_, ..., na.rm = FALSE, wt = NULL){
29 1
  UseMethod("dt_count", dt_)
30
}
31

32
#' @export
33
dt_count.default <- function(dt_, ..., na.rm = FALSE, wt = NULL){
34

35 1
  if (isFALSE(is.data.table(dt_)))
36 0
    .dt <- as.data.table(dt_)
37

38 1
  dots <- substitute(list(...))
39 1
  wt <- substitute(wt)
40

41 1
  if (na.rm)
42 1
    dt_ <- dt_[complete.cases(dt_)]
43

44 1
  if (!is.null(wt))
45 1
    return(dt_[, list(N = sum(eval(wt))), keyby = eval(dots)])
46

47 1
  dt_[, .N, keyby = eval(dots)]
48
}
49

Read our documentation on viewing source code .

Loading