Repository navigation
as_tibble.data.table() method? #5698
Description
Activity
Adding such method means extending dependencies of DT. We rather would like to reduce them, also Suggested dependencies. In this case there are many recursive dependencies as well.
Is there a reason why as_tibble.data.frame method doesn't work?
going via data.frame should work after looking at as.data.frame.data.table and what is underLine 2799 in 8803918
setattr(x, ".internal.selfref", NULL)
I believe there reason is presented by this minimal example, which doesn't need tibble to reproduce:
library(data.table) data(mpg, package = "ggplot2") mpg2 <- copy(mpg) identical(mpg, mpg2) #> [1] TRUE setDT(mpg2) mpg2 = as.data.frame(mpg2) identical(mpg, mpg2) #> [1] FALSE
Isn't this the
Enhances:dependency, and isn't the direction reversed, i.e., {data.table} would provideas.data.table.tibble()and {tibble} would provideas_tibble.data.table()?So the problem is that initial dataset to which you want to compare to isn't just data.frame. If we use normal data.frame it works as expected.
iris2 = copy(iris) identical(iris, iris2) # [1] TRUE setDT(iris2) iris2 = as.data.frame(iris2) identical(iris, iris2) # [1] TRUE
if
as_tibblewould go viaas.data.framethen all should work seamlessly, but it must be dispatching to second class attribute "data.frame" instead.
Defining the following should be sufficientas_tibble.data.table = function(x) as_tibble(as.data.frame(x))
because as.data.frame.data.table method handles removing its attributes.
I believe this problem is not only related to data.table but any package that defines class extending data.frame and uses custom attributes.
as_tibblewill assume it is standard data.frame and not go viaas_tibble.default. Therefore to resolve problem at the root it should be rather something like thatas_tibble.data.frame = function(x) { if (!identical(class(x), "data.frame")) return(as_tibble(as.data.frame(x))) ... # continue old as_tibble.data.frame body }
I noticed data.table would suffer from the same issue as tibble so I filled #5699 so problem can be addressed nicely without needing any package to add dependencies.
Reacted by Tim TaylorIndeed proposed one line change works as expected: https://github.com/Rdatatable/data.table/pull/5700/files
@jangorecki - do you want to raise this suggestion over at {tibble}? (I'm happy to do so if you'd prefer not to but didn't want to jump in over the top).
Thanks @TimTaylor
@ccsarapas I think that this issue is ready to be closed.
Reacted by Jan Gorecki
(I originally requested this at tidyverse/tibble/issues/1555, but they suggested requesting here instead.)
Would you consider adding a data.table method to
as_tibble()? On extremely cursory testing, it may be as simple as adaptingas_tibble.data.frame()with an extra line to remove the.internal.selfrefattribute:Created on 2023-09-22 with reprex v2.0.2