|
| 1 | +#' Fast Unnesting of Data Tables |
| 2 | +#' |
| 3 | +#' Quickly unnest data tables. |
| 4 | +#' |
| 5 | +#' @param dt the data table to nest |
| 6 | +#' @param col the column to unnest |
| 7 | +#' @param id the ID variable to unnest by |
| 8 | +#' |
| 9 | +#' @import data.table |
| 10 | +#' |
| 11 | +#' @export |
| 12 | +unnest_dt <- function(dt, col, id){ |
| 13 | + stopifnot(is.data.table(dt)) |
| 14 | + |
| 15 | + by <- substitute(id) |
| 16 | + col <- substitute(unlist(col, recursive = FALSE)) |
| 17 | + |
| 18 | + dt[, eval(col), by = eval(by)] |
| 19 | +} |
| 20 | + |
| 21 | +#' Fast Unnesting of Vectors |
| 22 | +#' |
| 23 | +#' Quickly nest vectors nested in a list column. |
| 24 | +#' |
| 25 | +#' @param dt the data table to nest |
| 26 | +#' @param cols the columns to unnest |
| 27 | +#' @param id the ID variable to unnest by |
| 28 | +#' @param name the names of the unnested vectors |
| 29 | +#' |
| 30 | +#' @import data.table |
| 31 | +#' |
| 32 | +#' @export |
| 33 | +unnest_vec_dt <- function(dt, cols, id, name){ |
| 34 | + stopifnot(is.data.table(dt)) |
| 35 | + |
| 36 | + by <- substitute(id) |
| 37 | + cols <- substitute(unlist(cols,recursive = FALSE)) |
| 38 | + |
| 39 | + dt <- dt[,eval(cols), by = eval(by)] |
| 40 | + setnames(dt, old = paste0("V", 1:length(name)), new = name) |
| 41 | + dt |
| 42 | +} |
0 commit comments