Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement as_data_frame.table() #23

Merged
merged 5 commits into from
Mar 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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