diff --git a/R/data_tabulate.R b/R/data_tabulate.R index c1f37ba2b..7245e7df1 100644 --- a/R/data_tabulate.R +++ b/R/data_tabulate.R @@ -785,6 +785,7 @@ as.table.datawizard_crosstab <- function( if (.is_grouped_df_xtab(x)) { x$Group <- NULL } + # first column contains the row names row_names <- as.character(x[[1]]) row_names[is.na(row_names)] <- "NA" @@ -805,6 +806,10 @@ as.table.datawizard_crosstab <- function( } # coerce to table result <- as.table(as.matrix(x)) + + dimnames_names <- c(attr(x, "varname"), attr(x, "by")) + names(attributes(result)$dimnames) <- dimnames_names + # if we don't want to simplify the table, we wrap it into a list if (!simplify) { result <- list(result) diff --git a/tests/testthat/_snaps/data_tabulate.md b/tests/testthat/_snaps/data_tabulate.md index ecb963e5c..153420ab5 100644 --- a/tests/testthat/_snaps/data_tabulate.md +++ b/tests/testthat/_snaps/data_tabulate.md @@ -925,10 +925,11 @@ as.table(x) Output [[1]] - 3 4 5 - 4 1 8 2 - 6 2 4 1 - 8 12 0 2 + mtcars$gear + mtcars$cyl 3 4 5 + 4 1 8 2 + 6 2 4 1 + 8 12 0 2 --- @@ -936,10 +937,11 @@ Code as.table(x, simplify = TRUE) Output - 3 4 5 - 4 1 8 2 - 6 2 4 1 - 8 12 0 2 + mtcars$gear + mtcars$cyl 3 4 5 + 4 1 8 2 + 6 2 4 1 + 8 12 0 2 --- @@ -947,10 +949,11 @@ as.table(x) Output [[1]] - 3 4 5 - 4 1 8 2 - 6 2 4 1 - 8 12 0 2 + gear + cyl 3 4 5 + 4 1 8 2 + 6 2 4 1 + 8 12 0 2 --- @@ -958,10 +961,11 @@ Code as.table(x, simplify = TRUE) Output - 3 4 5 - 4 1 8 2 - 6 2 4 1 - 8 12 0 2 + gear + cyl 3 4 5 + 4 1 8 2 + 6 2 4 1 + 8 12 0 2 --- @@ -969,15 +973,17 @@ as.table(x) Output [[1]] - 3 4 5 - 0 15 4 0 - 1 0 8 5 + gear + am 3 4 5 + 0 15 4 0 + 1 0 8 5 [[2]] - 3 4 5 - 4 1 8 2 - 6 2 4 1 - 8 12 0 2 + gear + cyl 3 4 5 + 4 1 8 2 + 6 2 4 1 + 8 12 0 2 --- @@ -986,15 +992,17 @@ as.table(x) Output $`am (0)` - 3 4 - 4 1 2 - 6 2 2 - 8 12 0 + gear + cyl 3 4 + 4 1 2 + 6 2 2 + 8 12 0 $`am (1)` - 4 5 - 4 6 2 - 6 2 1 - 8 0 2 + gear + cyl 4 5 + 4 6 2 + 6 2 1 + 8 0 2 diff --git a/tests/testthat/test-data_tabulate.R b/tests/testthat/test-data_tabulate.R index 83d976cef..c8b55e756 100644 --- a/tests/testthat/test-data_tabulate.R +++ b/tests/testthat/test-data_tabulate.R @@ -1167,6 +1167,7 @@ test_that("data_tabulate, table methods", { x <- data_tabulate(mtcars$cyl, mtcars$gear) expect_type(as.table(x), "list") expect_s3_class(as.table(x, simplify = TRUE), "table") + expect_named(dimnames(as.table(x)[[1]]), c("mtcars$cyl", "mtcars$gear")) expect_snapshot(as.table(x)) expect_snapshot(as.table(x, simplify = TRUE))