Skip to content

Commit

Permalink
add keep argument to dt_unnest
Browse files Browse the repository at this point in the history
Closes #38
  • Loading branch information
TysonStanley committed Jan 7, 2024
1 parent 57d0092 commit 4d5ed45
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
19 changes: 13 additions & 6 deletions R/unnest.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
#' Quickly unnest data tables, particularly those nested by \code{dt_nest()}.
#'
#' @param dt_ the data table to unnest
#' @param col the column to unnest
#' @param col the column to unnest
#' @param keep whether to keep the nested column, default is \code{TRUE}
#'
#' @examples
#'
Expand All @@ -19,14 +20,14 @@
#' @import data.table
#'
#' @export
dt_unnest <- function(dt_, col) {
dt_unnest <- function(dt_, col, keep = TRUE) {
UseMethod("dt_unnest", dt_)
}

#' @export
dt_unnest.default <- function(dt_, col) {
if (isFALSE(is.data.table(dt_))) {
dt_ <- as.data.table(dt_)
dt_unnest.default <- function(dt_, col, keep = TRUE) {
if (isFALSE(data.table::is.data.table(dt_))) {
dt_ <- data.table::as.data.table(dt_)
}

# col to unnest
Expand All @@ -45,7 +46,13 @@ dt_unnest.default <- function(dt_, col) {
others <- others[!others_class %in% c("list", "data.table", "data.frame", "tbl_df")]

# Join them all together
dt_[seq_len(.N), eval(col)[[1L]], by = others][dt_, on = others]
dt_2 <- dt_[seq_len(.N), eval(col)[[1L]], by = others]

if (isFALSE(keep)){
dt_[, deparse(col) := NULL]
}

dt_2[dt_, on = others]
}


Expand Down
4 changes: 3 additions & 1 deletion man/dt_unnest.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 18 additions & 1 deletion tests/testthat/test-dt_nest.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ starwars <- dplyr::starwars

test_that("dt_nest() works", {
res <- dt_nest(starwars, species, homeworld)
expect_is(dplyr::pull(res), "list")
expect_type(dplyr::pull(res), "list")

dplyr_res <- dplyr::group_nest(starwars, species, homeworld)

Expand Down Expand Up @@ -107,6 +107,23 @@ test_that("can unnest mixture of name and unnamed lists of same length", {
)
})


test_that("unnest keep argument", {
test_df <- data.table::data.table(x = 1:2)
nested_df <- data.table::data.table(id = 1L:2L, list_column = list(test_df, test_df))
expect_identical(
dt_unnest(nested_df, list_column, keep = TRUE),
data.table::data.table(id = c(1L,1L,2L,2L), x = c(1L,2L,1L,2L), list_column = list(test_df, test_df))
)

expect_identical(
dt_unnest(nested_df, list_column, keep = FALSE),
data.table::data.table(id = c(1L,1L,2L,2L), x = c(1L,2L,1L,2L))
)
})



# needs to be implemented in dt_hoist()
# test_that("hoist: elements must all be of same type", {
# df <- data.table::data.table(x = list(1, "a"),
Expand Down

0 comments on commit 4d5ed45

Please sign in to comment.