diff --git a/NEWS.md b/NEWS.md index 76ef587afe..bd733229e2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -16,17 +16,18 @@ 6. `fread()` and `fwrite()` can now handle file names in native and UTF-8 encoding, [#3078](https://github.com/Rdatatable/data.table/issues/3078). Thanks to Daniel Possenriede (@dpprdan) for reporting and fixing. -7. `DT[i]` now calls internal parallel subsetting code, [#2951](https://github.com/Rdatatable/data.table/issues/2951). Further, if `DT` has extra attributes (e.g. user defined or inherited via `as.data.table`) those attributes are now retained. Subsetting is significantly faster (as are many other operations) with factor columns rather than character. +7. `DT[i]` and `DT[i,cols]` now call internal parallel subsetting code, [#2951](https://github.com/Rdatatable/data.table/issues/2951). Subsetting is significantly faster (as are many other operations) with factor columns rather than character. ```R - N = 2e8 # 4GB data on 4-core CPU with 16GB RAM + N = 2e8 # 4GB data on 4-core CPU with 16GB RAM DT = data.table(ID = sample(LETTERS,N,TRUE), V1 = sample(5,N,TRUE), V2 = runif(N)) - w = which(DT$V1 > 3) # 40% of rows - # v1.12.0 v1.11.8 - system.time(DT[w]) # 0.8s 2.6s + w = which(DT$V1 > 3) # select 40% of rows + # v1.12.0 v1.11.8 + system.time(DT[w]) # 0.8s 2.6s DT[, ID := as.factor(ID)] - system.time(DT[w]) # 0.4s 2.3s + system.time(DT[w]) # 0.4s 2.3s + system.time(DT[w, c("ID","V2")]) # 0.3s 1.9s ``` @@ -46,6 +47,12 @@ 7. `split.data.table()` failed if `DT` had a factor column named `"x"`, [#3151](https://github.com/Rdatatable/data.table/issues/3151). Thanks to @tdeenes for reporting and fixing. +8. `DT[i,j]` now retains user-defined or inherited attributes; e.g. + ```R + attr(datasets::BOD,"reference") # "A1.4, p. 270" + attr(as.data.table(datasets::BOD)[2],"reference") # was NULL now "A1.4, p. 270" + ``` + #### NOTES 1. When data.table first loads it now checks the DLL's MD5. This is to detect installation issues on Windows when you upgrade and i) the DLL is in use by another R session and ii) the CRAN source version > CRAN binary binary which happens just after a new release (R prompts users to install from source until the CRAN binary is available). This situation can lead to a state where the package's new R code calls old C code in the old DLL; [R#17478](https://bugs.r-project.org/bugzilla/show_bug.cgi?id=17478), [#3056](https://github.com/Rdatatable/data.table/issues/3056). This broken state can persist until, hopefully, you experience a strange error caused by the mismatch. Otherwise, wrong results may occur silently. This situation applies to any R package with compiled code not just data.table, is Windows-only, and is long-standing. It has only recently been understood as it typically only occurs during the few days after each new release until binaries are available on CRAN. Thanks to Gabor Csardi for the suggestion to use `tools::checkMD5sums()`. diff --git a/R/data.table.R b/R/data.table.R index 1b11644977..c1c9526380 100644 --- a/R/data.table.R +++ b/R/data.table.R @@ -723,7 +723,8 @@ chmatch2 <- function(x, table, nomatch=NA_integer_) { if (!length(x)) return(null.data.table()) if (!length(leftcols)) { # basic x[i] subset, #2951 - return( if (is.null(irows)) x else .Call(CsubsetDT, x, irows, seq_along(x)) ) + if (is.null(irows)) return(shallow(x)) # e.g. DT[TRUE] (#3214); otherwise CsubsetDT would materialize a deep copy + else return(.Call(CsubsetDT, x, irows, seq_along(x)) ) } else { jisvars = names(i)[-leftcols] tt = jisvars %chin% names(x) @@ -795,6 +796,7 @@ chmatch2 <- function(x, table, nomatch=NA_integer_) { ansvars = j # x. and i. prefixes may be in here, and they'll be dealt with below # dups = FALSE here.. even if DT[, c("x", "x"), with=FALSE], we subset only the first.. No way to tell which one the OP wants without index. ansvals = chmatch(ansvars, names(x)) + if (anyNA(ansvals)) stop("column(s) not found: ", paste(ansvars[is.na(ansvals)],collapse=", ")) } } else if (is.numeric(j)) { j = as.integer(j) @@ -807,6 +809,7 @@ chmatch2 <- function(x, table, nomatch=NA_integer_) { ansvals = if (notj) setdiff(seq_along(x), j) else j } else stop("When with=FALSE, j-argument should be of type logical/character/integer indicating the columns to select.") # fix for #1440. if (!length(ansvals)) return(null.data.table()) + return(.Call(CsubsetDT, x, irows, ansvals)) } else { # with=TRUE and byjoin could be TRUE bynames = NULL allbyvars = NULL @@ -1258,70 +1261,65 @@ chmatch2 <- function(x, table, nomatch=NA_integer_) { # No grouping: 'by' = missing | NULL | character() | "" | list() # Considered passing a one-group to dogroups but it doesn't do the recycling of i within group, that's done here if (length(ansvars)) { - # TO DO: port more of this to C - ans = vector("list", length(ansvars)) - if (length(i) && length(icols)) { - if (allLen1 && allGrp1 && (is.na(nomatch) || !any(f__==0L))) { # nomatch=0 should drop rows in i that have no match - for (s in seq_along(icols)) { - target = icolsAns[s] - source = icols[s] - ans[[target]] = i[[source]] - if (address(ans[[target]]) == address(i[[source]])) ans[[target]] = copy(ans[[target]]) - } - } else { - ii = rep.int(indices__, len__) # following #1991 fix, allGrp1=FALSE always. TODO: revisit later - for (s in seq_along(icols)) { - target = icolsAns[s] - source = icols[s] - ans[[target]] = .Call(CsubsetVector,i[[source]],ii) # i.e. i[[source]][ii] - } - } - } - if (is.null(irows)) { - for (s in seq_along(xcols)) { # xcols means non-join x columns, since join columns come from i - target = xcolsAns[s] - source = xcols[s] - ans[[target]] = x[[source]] - # Temp fix for #921 - skip COPY until after evaluating 'jval' (scroll down). - # Unless 'with=FALSE' - can not be expressions but just column names. - if (!with && address(ans[[target]]) == address(x[[source]])) - ans[[target]] = copy(ans[[target]]) - else ans[[target]] = ans[[target]] + if (!(length(i) && length(icols))) { + # new in v1.12.0 to redirect to CsubsetDT in this case + if (!identical(xcolsAns, seq_along(xcolsAns)) || length(xcols)!=length(xcolsAns) || length(ansvars)!=length(xcolsAns)) { + stop("Internal error: xcolAns does not pass checks: ", length(xcolsAns), length(ansvars), length(xcols), paste(xcolsAns,collapse=",")) # nocov } + # Retained from old R way below (test 1542.01 checks shallow at this point) + # ' Temp fix for #921 - skip COPY until after evaluating 'jval' (scroll down). + # ' Unless 'with=FALSE' - can not be expressions but just column names. + ans = if (with && is.null(irows)) shallow(x, xcols) else .Call(CsubsetDT, x, irows, xcols) + setattr(ans, "names", ansvars) } else { - # TODO COMMENT HERE + # length(i) && length(icols) + if (is.null(irows)) { + stop("Internal error: irows is NULL when making join result at R level. Should no longer happen now we use CsubsetDT earlier.") # nocov + # TODO: Make subsetDT do a shallow copy when irows is NULL (it currently copies). Then copy only when user uses := or set* on the result + # by using NAMED/REFCNT on columns, with warning if they copy. Since then, even foo = DT$b would cause the next set or := to copy that + # column (so the warning is needed). To tackle that, we could have our own DT.NAMED attribute, perhaps. + # Or keep the rule that [.data.table always returns new memory, and create view() or view= as well, maybe cleaner. + } + ans = vector("list", length(ansvars)) + ii = rep.int(indices__, len__) # following #1991 fix + # TODO: if (allLen1 && allGrp1 && (is.na(nomatch) || !any(f__==0L))) then ii will be 1:nrow(i) [nomatch=0 should drop rows in i that have no match] + # But rather than that complex logic here at R level to catch that and do a shallow copy for efficiency, just do the check inside CsubsetDT + # to see if it passed 1:nrow(x) and then CsubsetDT should do the shallow copy safely and centrally. + # That R level branch was taken out in PR #3213 + + # TO DO: use CsubsetDT twice here and then remove this entire R level branch + for (s in seq_along(icols)) { + target = icolsAns[s] + source = icols[s] + ans[[target]] = .Call(CsubsetVector,i[[source]],ii) # i.e. i[[source]][ii] + } for (s in seq_along(xcols)) { target = xcolsAns[s] source = xcols[s] ans[[target]] = .Call(CsubsetVector,x[[source]],irows) # i.e. x[[source]][irows], but guaranteed new memory even for singleton logicals from R 3.1.0 } - } - # the address==address is a temp fix for R >= 3.1.0. TO DO: allow shallow copy here, then copy only when user uses := - # or set* on the result by using NAMED/REFCNT on columns, with warning if they copy. Since then, even foo = DT$b - # would cause the next set or := to copy that column (so the warning is needed). To tackle that, we could have our - # own DT.NAMED attribute, perhaps. - # Or keep the rule that [.data.table always returns new memory, and create view() or view= as well, maybe cleaner. - - setattr(ans, "names", ansvars) - if (haskey(x)) { - keylen = which.first(!key(x) %chin% ansvars)-1L - if (is.na(keylen)) keylen = length(key(x)) - len = length(rightcols) - # fix for #1268, #1704, #1766 and #1823 - chk = if (len && !missing(on)) !identical(head(key(x), len), names(on)) else FALSE - if ( (keylen>len || chk) && !.Call(CisOrderedSubset, irows, nrow(x))) { - keylen = if (!chk) len else 0L # fix for #1268 + setattr(ans, "names", ansvars) + if (haskey(x)) { + keylen = which.first(!key(x) %chin% ansvars)-1L + if (is.na(keylen)) keylen = length(key(x)) + len = length(rightcols) + # fix for #1268, #1704, #1766 and #1823 + chk = if (len && !missing(on)) !identical(head(key(x), len), names(on)) else FALSE + if ( (keylen>len || chk) && !.Call(CisOrderedSubset, irows, nrow(x))) { + keylen = if (!chk) len else 0L # fix for #1268 + } + ## check key on i as well! + ichk = is.data.table(i) && haskey(i) && + identical(head(key(i), length(leftcols)), names(i)[leftcols]) # i has the correct key, #3061 + if (keylen && (ichk || is.logical(i) || (.Call(CisOrderedSubset, irows, nrow(x)) && ((roll == FALSE) || length(irows) == 1L)))) # see #1010. don't set key when i has no key, but irows is ordered and roll != FALSE + setattr(ans,"sorted",head(key(x),keylen)) } - ## check key on i as well! - ichk = is.data.table(i) && haskey(i) && - identical(head(key(i), length(leftcols)), names(i)[leftcols]) # i has the correct key, #3061 - if (keylen && (ichk || is.logical(i) || (.Call(CisOrderedSubset, irows, nrow(x)) && ((roll == FALSE) || length(irows) == 1L)))) # see #1010. don't set key when i has no key, but irows is ordered and roll != FALSE - setattr(ans,"sorted",head(key(x),keylen)) + setattr(ans, "class", class(x)) # fix for #5296 + setattr(ans, "row.names", .set_row_names(nrow(ans))) + alloc.col(ans) } - setattr(ans, "class", class(x)) # fix for #5296 - setattr(ans, "row.names", .set_row_names(nrow(ans))) - if (!with || missing(j)) return(alloc.col(ans)) + if (!with || missing(j)) return(ans) SDenv$.SDall = ans SDenv$.SD = if (!length(othervars)) SDenv$.SDall else shallow(SDenv$.SDall, setdiff(ansvars, othervars)) diff --git a/inst/tests/tests.Rraw b/inst/tests/tests.Rraw index 4d93d6de7c..dc7dc1698f 100644 --- a/inst/tests/tests.Rraw +++ b/inst/tests/tests.Rraw @@ -7092,6 +7092,25 @@ if (!inherits(try(Rprofmem(NULL), silent=TRUE), "try-error")) { # in case R not test(1542, length(grep("000",readLines(f, warn=FALSE))), 1L) # one allocation for the RHS only unlink(f) } +# DT[TRUE] should shallow copy as v1.11.8 and earlier did (#3214); in future more will shallow copy too +DT = data.table(id = 1:5, key="id") +DT1 = DT[TRUE] +test(1542.01, address(DT1)!=address(DT)) +test(1542.02, address(DT1$id)==address(DT$id)) +test(1542.03, key(DT), "id") +test(1542.04, key(DT1), "id") +DT1[,newCol:=6:10] +test(1542.05, DT, data.table(id=1:5, key="id")) +test(1542.06, DT1, data.table(id=1:5, newCol=6:10, key="id")) +DT1[3, id:=6L] +test(1542.07, DT1, data.table(id=INT(1,2,6,4,5), newCol=6:10)) + +# current wrong behaviour (invalid key, #3215); root cause is the shallow exposed uniquely via DT[TRUE] +test(1542.08, DT$id, INT(1,2,6,4,5)) +test(1542.09, key(DT), "id") +# future correct behaviour : +# test(1542.10, DT$id, 1:5) +# test(1542.11, key(DT), "id") # rest of #1130 - merge doesn't copy, instead uses joins without keys. set.seed(1L) @@ -7103,7 +7122,7 @@ ans2 <- setDF(merge(setDT(d1), setDT(d2), by="A")) test(1543.1, ans1, ans2) ans1 <- suppressWarnings(merge(setDF(d1), setDF(d2), all=TRUE, by="A")) ans2 <- setDF(merge(setDT(d1), setDT(d2), all=TRUE, by="A")) -test(1542.2, ans1, ans2) +test(1543.2, ans1, ans2) # test duplicate name cases setnames(d2, c("A", "Y"), c("B", "A")) ans1 <- suppressWarnings(merge(setDF(d2), setDF(d1), by.x="B", by.y="A")) @@ -7445,7 +7464,7 @@ test(1562, melt(DT, measure=patterns("^g[12]"), variable.factor=FALSE), data.tab # fix for #1341 dt <- data.table(a = 1:10) test(1564.1, truelength(dt[, .SD]), 1025L) -test(1564.2, truelength(dt[a==5, .SD]), 1025L) +test(1564.2, truelength(dt[a==5, .SD]), 65L) test(1564.3, dt[a==5, .SD][, b := 1L], data.table(a=5L, b=1L)) # Fix for #1251, DT[, .N, by=a] and DT[, .(.N), by=a] uses GForce now diff --git a/src/subset.c b/src/subset.c index eee5fafdf0..601f6cc056 100644 --- a/src/subset.c +++ b/src/subset.c @@ -229,8 +229,8 @@ SEXP subsetDT(SEXP x, SEXP rows, SEXP cols) { if (!length(x)) return(x); // return empty list // check index once up front for 0 or NA, for branchless subsetVectorRaw which is repeated for each column - bool anyNA=false, orderedSubset=false; - if (check_idx(rows, length(VECTOR_ELT(x,0)), &anyNA, &orderedSubset) != NULL) { + bool anyNA=false, orderedSubset=true; // true for when rows==null (meaning all rows) + if (!isNull(rows) && check_idx(rows, length(VECTOR_ELT(x,0)), &anyNA, &orderedSubset) != NULL) { SEXP max = PROTECT(ScalarInteger(length(VECTOR_ELT(x,0)))); nprotect++; rows = PROTECT(convertNegAndZeroIdx(rows, max, ScalarLogical(TRUE))); nprotect++; const char *err = check_idx(rows, length(VECTOR_ELT(x,0)), &anyNA, &orderedSubset); @@ -248,12 +248,19 @@ SEXP subsetDT(SEXP x, SEXP rows, SEXP cols) { // so includes row.names (oddly, given other dims aren't) and "sorted", dealt with below SET_TRUELENGTH(ans, LENGTH(ans)); SETLENGTH(ans, LENGTH(cols)); - for (int i=0; i