# group_data -------------------------------------------------------------- test_that("group_data() returns a data frame", { df <- data.frame(x = 1:3) gd <- group_data(df) expect_s3_class(gd, "data.frame", exact = TRUE) expect_equal(gd$.rows, list_of(1:3)) }) test_that("group_data() returns a tibble", { df <- tibble(x = 1:3) gd <- group_data(df) expect_s3_class(gd, "tbl_df") expect_equal(gd, tibble(".rows" := list_of(1:3))) }) test_that("group_data() returns a tibble", { df <- tibble(x = c(1, 1, 2)) gf <- group_by(df, x) gd <- group_data(gf) expect_s3_class(gd, "tbl_df") expect_equal( gd, tibble(x = c(1, 2), ".rows" := list_of(1:2, 3L)), ignore_attr = TRUE ) }) test_that("group_data(% group_keys(x), "deprecated") expect_equal(out, tibble(x = 1)) }) # group_indices() --------------------------------------------------------- test_that("no arg group_indices() is deprecated", { df <- tibble(x = 1) expect_warning(out <- summarise(df, id = group_indices()), "deprecated") expect_equal(out, tibble(id = 1)) }) test_that("group_indices(...) is deprecated", { rlang::local_options(lifecycle_verbosity = "error") df <- tibble(x = 1, y = 2) expect_error(df %>% group_indices(x), "deprecated") }) test_that("group_indices(...) still works though", { rlang::local_options(lifecycle_verbosity = "quiet") df <- tibble(x = 1, y = 2) out <- df %>% group_indices(x) expect_equal(out, 1) }) test_that("group_indices() returns expected values", { df <- tibble(x = c("b", "a", "b")) gf <- group_by(df, x) expect_equal(group_indices(df), c(1, 1, 1)) expect_equal(group_indices(gf), c(2, 1, 2)) }) test_that("group_indices() handles 0 rows data frames (#5541)", { df <- new_grouped_df( data.frame(x = integer(), y = integer()), groups = data.frame(x=0, .rows = vctrs::list_of(1:1000)) ) expect_equal(group_indices(df), integer()) }) # group_size -------------------------------------------------------------- test_that("ungrouped data has 1 group, with group size = nrow()", { df <- tibble(x = rep(1:3, each = 10), y = rep(1:6, each = 5)) expect_equal(n_groups(df), 1L) expect_equal(group_size(df), 30) }) test_that("rowwise data has one group for each group", { rw <- rowwise(mtcars) expect_equal(n_groups(rw), 32) expect_equal(group_size(rw), rep(1, 32)) }) test_that("group_size correct for grouped data", { df <- tibble(x = rep(1:3, each = 10), y = rep(1:6, each = 5)) %>% group_by(x) expect_equal(n_groups(df), 3L) expect_equal(group_size(df), rep(10, 3)) }) # n_groups ---------------------------------------------------------------- test_that("n_groups respects zero-length groups (#341)", { df <- tibble(x = factor(1:3, levels = 1:4)) %>% group_by(x, .drop = FALSE) expect_equal(n_groups(df), 4) })