From a26027ba2f614e13d64aa16434e4cb229ec1f86e Mon Sep 17 00:00:00 2001 From: Buyan Khurelbaatar <158336401+buyan-kh@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:24:48 +0000 Subject: [PATCH] compare ordered factors in level order --- R/DuckDBTable-utils.R | 153 ++++++++++++++++++++++++++++- tests/testthat/test-factor-order.R | 66 +++++++++++++ 2 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 tests/testthat/test-factor-order.R diff --git a/R/DuckDBTable-utils.R b/R/DuckDBTable-utils.R index 8e47c13..b5a47bb 100644 --- a/R/DuckDBTable-utils.R +++ b/R/DuckDBTable-utils.R @@ -427,8 +427,114 @@ ORDER BY function_name", ### Group generic methods ### +# Position of a stored label in a factor's levels, or NA when it is missing +# or not one of those levels. Comparisons of an ordered factor use this, the +# way base R compares the integer codes, instead of the text of the label. +.levelCodeExpr <- function(col, levels) { + text <- call("as.character", col) + expr <- NA_integer_ + for (i in rev(seq_along(levels))) { + expr <- call("ifelse", call("==", text, levels[[i]]), as.integer(i), expr) + } + expr +} + +.opsSides <- function(obj, n, collevels) { + vals <- as.list(obj) + nms <- names(obj) + entries <- if (is.null(nms)) { + rep(list(NULL), length(vals)) + } else { + lapply(nms, function(nm) collevels[[nm]]) + } + list(vals = rep_len(vals, n), entries = rep_len(entries, n)) +} + +.opsInvolvesFactor <- function(x, fin1, fin2) { + any(c(names(fin1), names(fin2)) %in% names(x@collevels)) +} + +# One relational comparison. NULL means neither side is a factor, so the +# caller keeps the ordinary comparison. An unordered factor is not ordered +# by its labels: the result is NA, and the caller warns once. +.factorRelExpr <- function(.Generic, lhs, rhs, lhs_entry, rhs_entry) { + if (is.null(lhs_entry) && is.null(rhs_entry)) { + return(NULL) + } + if ((!is.null(lhs_entry) && !isTRUE(lhs_entry[["ordered"]])) || + (!is.null(rhs_entry) && !isTRUE(rhs_entry[["ordered"]]))) { + # a bare NA is an untyped NULL, which DuckDB reads back as an integer + return(call("as.logical", NA)) + } + lev <- if (!is.null(lhs_entry)) lhs_entry[["levels"]] else rhs_entry[["levels"]] + code <- function(value, entry) { + if (!is.null(entry)) { + return(.levelCodeExpr(value, entry[["levels"]])) + } + if (is.atomic(value) && length(value) == 1L) { + return(as.integer(match(as.character(value), lev))) + } + .levelCodeExpr(value, lev) + } + call(.Generic, code(lhs, lhs_entry), code(rhs, rhs_entry)) +} + +.plainRelExpr <- function(.Generic, a, b, ta, tb) { + ans <- call(.Generic, a, b) + if (!any(c(ta, tb) %in% "double")) { + return(ans) + } + nan <- c(if (identical(ta, "double")) call("is.nan", a), + if (identical(tb, "double")) call("is.nan", b)) + if (length(nan) == 0L) { + return(ans) + } + cond <- if (length(nan) == 1L) nan[[1L]] else call("|", nan[[1L]], nan[[2L]]) + call("ifelse", cond, NA, ans) +} + +.opsFactorCompare <- function(.Generic, x, fin1, fin2, fout, t1, t2) { + n <- max(length(fin1), length(fin2)) + left <- .opsSides(fin1, n, x@collevels) + right <- .opsSides(fin2, n, x@collevels) + ta <- rep_len(if (is.null(t1)) "other" else t1, n) + tb <- rep_len(if (is.null(t2)) "other" else t2, n) + for (i in seq_len(n)) { + e1 <- left$entries[[i]] + e2 <- right$entries[[i]] + if (is.null(e1) || is.null(e2)) { + next + } + if (xor(isTRUE(e1[["ordered"]]), isTRUE(e2[["ordered"]]))) { + stop("comparison of these types is not implemented") + } + if (isTRUE(e1[["ordered"]]) && !identical(e1[["levels"]], e2[["levels"]])) { + stop("level sets of factors are different") + } + } + unordered <- function(entry) !is.null(entry) && !isTRUE(entry[["ordered"]]) + if (any(vapply(c(left$entries, right$entries), unordered, logical(1L)))) { + warning(gettextf("%s not meaningful for factors", sQuote(.Generic))) + } + exprs <- Map(function(a, b, e1, e2, ta, tb) { + got <- .factorRelExpr(.Generic, a, b, e1, e2) + if (!is.null(got)) { + return(got) + } + .plainRelExpr(.Generic, a, b, ta, tb) + }, left$vals, right$vals, left$entries, right$entries, ta, tb) + # the result is logical, so it is no longer a factor + datacols <- setNames(as.expression(exprs), fout) + replaceSlots(x, datacols = datacols, + collevels = setNames(list(), character()), check = FALSE) +} + #' @importFrom stats setNames .Ops.DuckDBTable <- function(.Generic, x, fin1, fin2, fout, t1 = NULL, t2 = NULL) { + if (.Generic %in% c("<", "<=", ">", ">=") && + .opsInvolvesFactor(x, fin1, fin2)) { + return(.opsFactorCompare(.Generic, x, fin1, fin2, fout, t1, t2)) + } if (.Generic %in% c("==", "!=", "<", "<=", ">", ">=") && any(c(t1, t2) %in% "double")) { n <- max(length(fin1), length(fin2)) @@ -739,12 +845,49 @@ setMethod("log", "DuckDBTable", function(x, base = exp(1)) { res[[1L]] } +# min, max and range of an ordered factor follow the level order, then come +# back as an ordered factor. An unordered factor has no order, as in base R. +.orderedExtreme <- function(x, entry, generic, na.rm) { + levels <- entry[["levels"]] + coded <- replaceSlots( + x, + datacols = as.expression(setNames( + list(.levelCodeExpr(x@datacols[[1L]], levels)), names(x@datacols))), + collevels = setNames(list(), character()), + check = FALSE) + specs <- switch(generic, + min = list(value = .aggrSpec("min", "keep", Inf)), + max = list(value = .aggrSpec("max", "keep", -Inf)), + range = list(min = .aggrSpec("min", "keep", Inf), + max = .aggrSpec("max", "keep", -Inf))) + ind <- unname(unlist(.aggregate(coded, specs, na.rm), use.names = FALSE)) + generics <- if (generic == "range") c("min", "max") else generic + for (i in seq_along(ind)) { + if (is.infinite(ind[[i]])) { + g <- generics[[i]] + warning(sprintf("no non-missing arguments to %s; returning %s", + g, if (g == "max") "-Inf" else "Inf"), call. = FALSE) + ind[[i]] <- NA_integer_ + } + } + ordered(levels[ind], levels = levels) +} + #' @export setMethod("Summary", "DuckDBTable", function(x, ..., na.rm = FALSE) { if (...length() != 0L) { stop("'", .Generic, "' of a DuckDB object takes a single object, ", "not several; the other arguments would be ignored") } + if (length(x@datacols) == 1L && .Generic %in% c("min", "max", "range")) { + entry <- x@collevels[[names(x@datacols)[[1L]]]] + if (!is.null(entry)) { + if (!isTRUE(entry[["ordered"]])) { + stop(gettextf("%s not meaningful for factors", sQuote(.Generic))) + } + return(.orderedExtreme(x, entry, .Generic, na.rm)) + } + } one <- function(spec) .aggregate(x, list(value = spec), na.rm)[["value"]] # sum() of integers is an integer in base R sumInteger <- function(value) { @@ -1335,7 +1478,15 @@ setMethod("table", "DuckDBTable", function(x, ...) { isMissing <- function(j) { if (is.double(j) && useNA != "no") is.na(j) & !is.nan(j) else is.na(j) } - levels <- lapply(values, function(j) { + # a factor keeps its recorded levels, in that order, including ones that + # do not occur. anything else is the sorted values that do occur. + col_names <- names(x@datacols) + levels <- lapply(seq_along(values), function(i) { + j <- values[[i]] + entry <- x@collevels[[col_names[[i]]]] + if (!is.null(entry)) { + return(entry[["levels"]]) + } lev <- sort(unique(j[!is.na(j)])) if (is.double(j) && useNA != "no" && any(is.nan(j))) lev <- c(lev, NaN) diff --git a/tests/testthat/test-factor-order.R b/tests/testthat/test-factor-order.R new file mode 100644 index 0000000..9752e15 --- /dev/null +++ b/tests/testthat/test-factor-order.R @@ -0,0 +1,66 @@ +# An ordered factor follows its level order. An unordered factor has none. + +.factor_col <- function(labels, levels, ordered) { + path <- tempfile(fileext = ".parquet") + arrow::write_parquet(data.frame(id = letters[seq_along(labels)], ct = labels), path) + list(path = path, + col = DuckDBDataFrame( + path, datacols = "ct", keycol = "id", + collevels = list(ct = list(levels = levels, ordered = ordered)))[["ct"]], + factor = if (ordered) ordered(labels, levels = levels) else factor(labels, levels = levels)) +} + +test_that("an ordered factor compares and aggregates in level order", { + lev <- c("low", "med", "high") + got <- .factor_col(c("low", "high", "med", "low"), lev, TRUE) + on.exit(unlink(got$path)) + x <- got$col + f <- got$factor + + expect_identical(min(x), min(f)) + expect_identical(max(x), max(f)) + expect_identical(range(x), range(f)) + expect_identical(unname(as.vector(x < "med")), unname(f < "med")) + expect_identical(unname(as.vector(x <= "med")), unname(f <= "med")) + expect_identical(unname(as.vector(x > "med")), unname(f > "med")) + expect_identical(unname(as.vector(x >= "high")), unname(f >= "high")) + expect_identical(unname(as.vector("med" < x)), unname("med" < f)) + expect_identical(unname(as.vector(x < "nope")), unname(f < "nope")) + + expect_identical(as.vector(table(x)), as.vector(table(f))) + expect_identical(names(table(x)), names(table(f))) +}) + +test_that("table of a factor keeps unused levels, and a missing value stays missing", { + lev <- c("low", "med", "high") + got <- .factor_col(c("low", NA, "low"), lev, TRUE) + on.exit(unlink(got$path)) + x <- got$col + f <- got$factor + + expect_identical(min(x), min(f)) + expect_identical(min(x, na.rm = TRUE), min(f, na.rm = TRUE)) + expect_identical(unname(as.vector(x < "med")), unname(f < "med")) + expect_identical(as.vector(table(x)), as.vector(table(f))) + expect_identical(names(table(x)), names(table(f))) + expect_identical(as.vector(table(x, useNA = "ifany")), + as.vector(table(f, useNA = "ifany"))) + expect_identical(names(table(x, useNA = "ifany")), + names(table(f, useNA = "ifany"))) +}) + +test_that("an unordered factor does not compare or take min and max", { + got <- .factor_col(c("b", "a", "b", NA), c("a", "b", "c"), FALSE) + on.exit(unlink(got$path)) + x <- got$col + + expect_warning(res <- x < "b", "not meaningful for factors") + expect_identical(unname(as.vector(res)), rep(NA, 4L)) + expect_error(min(x), "not meaningful for factors") + expect_error(max(x), "not meaningful for factors") + expect_error(range(x), "not meaningful for factors") + + tab <- table(x) + expect_identical(as.vector(tab), c(1L, 2L, 0L)) + expect_identical(names(tab), c("a", "b", "c")) +})