Skip to content

Commit

Permalink
Revert "don't pass on ..."
Browse files Browse the repository at this point in the history
This reverts commit 5cb62d2.
  • Loading branch information
krlmlr committed Nov 12, 2017
1 parent 2b219d2 commit bb44ed6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 7 deletions.
36 changes: 30 additions & 6 deletions R/new.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,49 @@
#' Creates a subclass of a tibble.
#'
#' @param x A tibble-like object
#' @param ... Passed on to [structure()]
#' @param nrow The number of rows, guessed from the data by default
#' @param subclass Subclasses to assign to the new object, default: none
#' @export
new_tibble <- function(x, nrow = NULL, subclass = NULL) {
new_tibble <- function(x, ..., nrow = NULL, subclass = NULL) {
stopifnot(is.list(x))
stopifnot(has_nonnull_names(x))

x <- update_tibble_attrs(x, ...)
x <- set_tibble_class(x, subclass = subclass)
# Make sure that we override any row names that
# may have been there previously, in x or in ...
if (is.null(nrow)) nrow <- guess_nrow(x)
attr(x, "row.names") <- .set_row_names(nrow)
validate_nrow(x)
x
}

update_tibble_attrs <- function(x, ...) {
# Can't use structure() here because it breaks the row.names attribute
attribs <- list(...)

# reduce2() is not in the purrr compat layer
nested_attribs <- map2(names(attribs), attribs, function(name, value) set_names(list(value), name))
x <- reduce(
.init = x,
nested_attribs,
function(x, attr) {
if (!is.null(attr[[1]])) {
attr(x, names(attr)) <- attr[[1]]
}
x
}
)

x
}

set_tibble_class <- function(x, subclass = NULL) {
class(x) <- c(subclass, "tbl_df", "tbl", "data.frame")
x
}

guess_nrow <- function(x) {
if (!is.null(.row_names_info(x, 0L))) .row_names_info(x, 2L)
else if (length(x) == 0) 0L
Expand All @@ -37,8 +66,3 @@ validate_nrow <- function(x) {

invisible(x)
}

set_tibble_class <- function(x, subclass = NULL) {
class(x) <- c(subclass, "tbl_df", "tbl", "data.frame")
x
}
6 changes: 5 additions & 1 deletion man/new_tibble.Rd

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

4 changes: 4 additions & 0 deletions tests/testthat/test-tbl-df.R
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ test_that("is_tibble", {
test_that("new_tibble", {
tbl <- new_tibble(
data.frame(a = 1:3),
attr1 = "value1",
attr2 = 2,
subclass = "nt"
)

Expand All @@ -310,6 +312,8 @@ test_that("new_tibble", {
unclass(tbl),
structure(
list(a = 1:3),
attr1 = "value1",
attr2 = 2,
.Names = "a",
row.names = .set_row_names(3L)
)
Expand Down

0 comments on commit bb44ed6

Please sign in to comment.