From 7b36bff532dddbfc10f1ef6799f17f04868864e2 Mon Sep 17 00:00:00 2001 From: jangorecki Date: Mon, 10 Jun 2019 18:18:07 +0530 Subject: [PATCH] dt array method more smart, closes #3636 --- NEWS.md | 2 ++ R/as.data.table.R | 9 +++++++-- inst/tests/tests.Rraw | 9 +++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3da712bc7f..a045303e3f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -132,6 +132,8 @@ 19. `merge.data,table` now retains any custom classes of the first argument, [#1378](https://github.com/Rdatatable/data.table/issues/1378). Thanks to @michaelquinn32 for reopening. +20. `as.data.table.array` method now properly handles the case when some of dimension names are `NULL`, [#3636](https://github.com/Rdatatable/data.table/issues/3636). + #### NOTES 1. `rbindlist`'s `use.names="check"` now emits its message for automatic column names (`"V[0-9]+"`) too, [#3484](https://github.com/Rdatatable/data.table/pull/3484). See news item 5 of v1.12.2 below. diff --git a/R/as.data.table.R b/R/as.data.table.R index 535e6f7ec6..8b87a9bc2e 100644 --- a/R/as.data.table.R +++ b/R/as.data.table.R @@ -90,10 +90,15 @@ as.data.table.array = function(x, keep.rownames=FALSE, key=NULL, sorted=TRUE, va if (!missing(sorted) && !is.null(key)) stop("Please provide either 'key' or 'sorted', but not both.") - dnx = dimnames(x) # NULL dimnames will create integer keys, not character as in table method - val = rev(if (is.null(dnx)) lapply(dx, seq.int) else dnx) + val = if (is.null(dnx)) { + lapply(dx, seq.int) + } else if (any(nulldnx<-sapply(dnx, is.null))) { + dnx[nulldnx] = lapply(dx[nulldnx], seq.int) #3636 + dnx + } else dnx + val = rev(val) if (is.null(names(val)) || all(!nzchar(names(val)))) setattr(val, 'names', paste0("V", rev(seq_along(val)))) if (value.name %chin% names(val)) diff --git a/inst/tests/tests.Rraw b/inst/tests/tests.Rraw index ea6107383f..7b892c2692 100644 --- a/inst/tests/tests.Rraw +++ b/inst/tests/tests.Rraw @@ -14977,6 +14977,15 @@ DT = data.table( test(2054, DT[order(C)[1:5], B, verbose=TRUE], c('b', 'b', 'c', 'c', 'a'), output = 'order optimisation is on') +# as.data.table.array some of dimnames are NULL #3636 +a = array(1:8, dim=c(2L,2L,2L), dimnames=list(NULL, NULL, as.character(1:2))) +ans = data.table(V1=c(1L,1L,1L,1L,2L,2L,2L,2L), + V2=c(1L,1L,2L,2L,1L,1L,2L,2L), + V3=c("1","2","1","2","1","2","1","2"), + value=c(1L,5L,3L,7L,2L,6L,4L,8L), + key=c("V1","V2","V3")) +test(2055, as.data.table(a), ans) + ################################### # Add new tests above this line #