Skip to content

Commit

Permalink
Merge pull request #23 from krlmlr/feature/22-as_data_frame.table
Browse files Browse the repository at this point in the history
- New `as_data_frame.table()` with argument `n` to control name of count column (#22, #23).
  • Loading branch information
krlmlr committed Mar 10, 2016
2 parents cd81dc6 + 4095077 commit 512effc
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ S3method(as_data_frame,"NULL")
S3method(as_data_frame,data.frame)
S3method(as_data_frame,list)
S3method(as_data_frame,matrix)
S3method(as_data_frame,table)
S3method(as_data_frame,tbl_df)
S3method(format_v,character)
S3method(format_v,default)
Expand Down
9 changes: 8 additions & 1 deletion R/dataframe.R
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ lst_ <- function(xs) {
#' with more efficient methods for matrices and data frames.
#'
#' This is an S3 generic. tibble includes methods for data frames (adds tbl_df
#' classes), tbl_dfs (trivial!), lists, and matrices.
#' classes), tbl_dfs (trivial!), lists, matrices, and tables.
#'
#' @param x A list. Each element of the list must have the same length.
#' @param ... Other arguments passed on to individual methods.
Expand Down Expand Up @@ -188,6 +188,13 @@ as_data_frame.matrix <- function(x, ...) {
x
}

#' @export
#' @param n Name for count column, default: \code{"n"}.
#' @rdname as_data_frame
as_data_frame.table <- function(x, n = "n", ...) {
as_data_frame(as.data.frame(x, responseName = n, stringsAsFactors = FALSE))
}

#' @export
#' @rdname as_data_frame
as_data_frame.NULL <- function(x, ...) {
Expand Down
7 changes: 6 additions & 1 deletion man/as_data_frame.Rd

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

12 changes: 12 additions & 0 deletions tests/testthat/test-data_frame.R
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,18 @@ test_that("NULL makes 0 x 0 tbl_df", {
expect_equal(dim(nnnull), c(0L, 0L))
})


test_that("Can convert tables to data frame", {
mtcars_table <- xtabs(mtcars, formula = ~vs+am+cyl)

mtcars_tbl <- as_data_frame(mtcars_table)
expect_equal(names(mtcars_tbl), c(names(dimnames(mtcars_table)), "n"))

mtcars_tbl <- as_data_frame(mtcars_table, "Freq")
expect_equal(names(mtcars_tbl), c(names(dimnames(mtcars_table)), "Freq"))
})


# Validation --------------------------------------------------------------

test_that("2d object isn't a valid column", {
Expand Down

0 comments on commit 512effc

Please sign in to comment.