1
#' Uncount
2
#'
3
#' Uncount a counted data table
4
#'
5
#' @param dt_ the data table to uncount
6
#' @param weights the counts for each
7
#' @param .remove should the weights variable be removed?
8
#' @param .id an optional new id variable, providing a unique id for each row
9
#'
10
#' @examples
11
#'
12
#' library(data.table)
13
#'
14
#' dt_count <- data.table(
15
#'   x = LETTERS[1:3],
16
#'   w = c(2,1,4)
17
#' )
18
#' uncount <- dt_uncount(dt_count, w, .id = "id")
19
#' uncount   # note that if .remove = TRUE or .id is not null
20
#'           # this won't print the first time
21
#'           # due to a printing behavior in data.table
22
#'
23
#'
24
#' @import data.table
25
#'
26
#' @export
27
dt_uncount <- function(dt_, weights, .remove = TRUE, .id = NULL){
28 1
  UseMethod("dt_uncount", dt_)
29
}
30

31
#' @export
32
dt_uncount.default <- function(dt_, weights, .remove = TRUE, .id = NULL){
33

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

37 1
  w <- substitute(weights)
38 1
  dt_ <- dt_[rep(1:.N, eval(w))]
39

40 1
  if (.remove)
41 1
    dt_[, `:=`(paste(w), NULL)]
42

43 1
  if (!is.null(.id))
44 1
    dt_[, `:=`(.id, 1:.N)]
45

46 1
  dt_
47
}

Read our documentation on viewing source code .

Loading