diff --git a/NEWS.md b/NEWS.md index 35806cf28..14972081d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -129,6 +129,8 @@ rowwiseDT( 17. Assignment with `:=` to an S4 slot of an under-allocated data.table now works, [#6704](https://github.com/Rdatatable/data.table/issues/6704). Thanks @MichaelChirico for the report and fix. +18. `as.data.table()` method for `data.frame`s (especially those with extended classes) is more consistent with `as.data.frame()` with respect to rention of attributes, [#5699](https://github.com/Rdatatable/data.table/issues/5699). Thanks @jangorecki for the report and fix. + ## NOTES 1. There is a new vignette on joins! See `vignette("datatable-joins")`. Thanks to Angel Feliz for authoring it! Feedback welcome. This vignette has been highly requested since 2017: [#2181](https://github.com/Rdatatable/data.table/issues/2181). diff --git a/R/as.data.table.R b/R/as.data.table.R index 3137f7532..6669c0f02 100644 --- a/R/as.data.table.R +++ b/R/as.data.table.R @@ -214,6 +214,7 @@ as.data.table.list = function(x, } as.data.table.data.frame = function(x, keep.rownames=FALSE, key=NULL, ...) { + if (!identical(class(x), "data.frame")) return(as.data.table(as.data.frame(x))) if (!isFALSE(keep.rownames)) { # can specify col name to keep.rownames, #575; if it's the same as key, # kludge it to 'rn' since we only apply the new name afterwards, #4468 diff --git a/inst/tests/tests.Rraw b/inst/tests/tests.Rraw index f5c789ba2..5fddeecf1 100644 --- a/inst/tests/tests.Rraw +++ b/inst/tests/tests.Rraw @@ -20742,3 +20742,14 @@ test(2301.1, DT[order(a, method="auto")], error="no support for sorting by metho test(2301.2, DT[order(a, b, decreasing=c(TRUE, FALSE))], DT[order(-a, b)]) test(2301.3, DT[order(a, -b, decreasing=c(TRUE, TRUE))], error="Mixing '-' with vector decreasing") test(2301.4, DT[order(a, b, decreasing=c(TRUE, TRUE, FALSE))], error="decreasing= has length 3") + +# as.data.table should remove extra attributes from extended data.frames #5699 +x = data.frame(a=c(1,5,3), b=c(2,4,6)) +class(x) = c("tbl", "data.frame") +attr(x, "t1") = "a" +as.data.frame.tbl = function(x) { + attr(x, "t1") = NULL + class(x) = "data.frame" + x +} +test(2302, attr(as.data.table(y), "t1"), attr(as.data.frame(y), "t1"))