Skip to content

Commit

Permalink
fix: new_tibble() and as_tibble() support attributes named "n"
Browse files Browse the repository at this point in the history
…and `"x"`
  • Loading branch information
krlmlr committed Apr 13, 2024
1 parent 975fa34 commit 4b7dcc7
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
3 changes: 2 additions & 1 deletion R/as_tibble.R
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ lst_to_tibble <- function(x, .rows, .name_repair, lengths = NULL, call = caller_
x <- unclass(x)
x <- set_repaired_names(x, repair_hint = TRUE, .name_repair, call = call)
x <- check_valid_cols(x, call = call)
recycle_columns(x, .rows, lengths)
x <- recycle_columns(x, .rows, lengths)
x
}

check_valid_cols <- function(x, pos = NULL, call = caller_env()) {
Expand Down
21 changes: 17 additions & 4 deletions R/new.R
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,28 @@ new_tibble <- function(x, ..., nrow = NULL, class = NULL, subclass = NULL) {
class <- c(class[!class %in% tibble_class], tibble_class_no_data_frame)
}

slots <- c("x", "n", "class")
args[slots] <- list(x, nrow, class)

# `new_data_frame()` restores compact row names
# Can't add to the assignment above, a literal NULL would be inserted otherwise
args[["row.names"]] <- NULL

# Attributes n and x are special and must be assigned after construction
an <- args[["n"]]
ax <- args[["x"]]
args[["n"]] <- NULL
args[["x"]] <- NULL

# need exec() to avoid evaluating language attributes (e.g. rsample)
exec(new_data_frame, !!!args)
out <- exec(new_data_frame, x = x, n = nrow, !!!args, class = class)

if (!is.null(an)) {
attr(out, "n") <- an
}

if (!is.null(ax)) {
attr(out, "x") <- ax
}

out
}

#' @description
Expand Down
17 changes: 17 additions & 0 deletions tests/testthat/test-new.R
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,23 @@ test_that("new_tibble() supports missing `nrow` (#781)", {
expect_identical(new_tibble(list(a = 1:3)), tibble(a = 1:3))
})

test_that("new_tibble() keeps x and n attributes", {
expect_identical(
attr(new_tibble(list(x = 1), n = 2, nrow = 1), "n"),
2
)

expect_identical(
attr(new_tibble(structure(list(x = 1), n = 2), nrow = 1), "n"),
2
)

expect_identical(
attr(new_tibble(structure(list(x = 1), x = "value"), nrow = 1), "x"),
"value"
)
})

test_that("new_tibble() supports language objects", {
expect_identical(
new_tibble(list(), foo = quote(bar())),
Expand Down

0 comments on commit 4b7dcc7

Please sign in to comment.