Suppose I have a tibble
and decided to constructed a new subclass with help of new_tibble()
:
library(dplyr, warn.conflicts = FALSE)
library(tibble, warn.conflicts = FALSE)
set.seed(123)
x <- tibble(x = rnorm(5))
x <- new_tibble(x, nrow = nrow(x), class = "go_away")
class(x)
#> [1] "go_away" "tbl_df" "tbl" "data.frame"
What is the most efficient way to make the object x
iterate with the dplyr
verbs without keeping the memory of the newly created subclass?
For example, if I try:
mutate(x, tibble(y = 1)) %>% class()
#> [1] "go_away" "tbl_df" "tbl" "data.frame"
The go_away
signature is still there.
But, if I do this:
mutate.go_away <- function(.data, ...) {
mutate(as_tibble(.data), ...)
}
mutate(x, tibble(y = 1)) %>% class()
#> [1] "tbl_df" "tbl" "data.frame"
mutate(x, y = 1) %>% class()
#> [1] "tbl_df" "tbl" "data.frame"
mutate(x, x) %>% class()
#> [1] "tbl_df" "tbl" "data.frame"
The problem is apparently solved (at least for mutate
).
Sadly, this solution forces me to create a new method for all the verbs in the tidyverse
. This would make sense if I wanted the go_away
class to have a life on its own, but my objective is quite the opposite: iteration among tibbles and data.frames should always fallback to the default signature
#> [1] "'tbl_df'" "'tbl'" "'data.frame'"
… and nothing else.
Any thoughts on how this could be achieved without having to extend dplyr
verbs, like tsibble did (here and here)?
Created on 2021-06-16 by the reprex package (v2.0.0)