From 128a1c423fb092662deffc13b17769fe39bfb274 Mon Sep 17 00:00:00 2001 From: LiNk-NY Date: Tue, 1 Dec 2026 16:40:27 -0500 Subject: [PATCH] Fix ldaFunction score sign for reference-class features ldaFunction() added the signed class-mean difference to the unsigned (absolute) scaled LDA coefficient. For features enriched in the first factor level this gave (coeff - |diff|) / 2 instead of -(|diff| + coeff) / 2, shrinking the score or flipping it to the other class when coeff > |diff|, so results depended on level order. Average the magnitudes as in LEfSe and apply the sign of the mean difference. Update the ldaFunction unit test, which encoded the biased value (0 instead of -9), and add a level-reversal check. Closes #104 Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 4 ++++ R/lefser.R | 4 +++- tests/testthat/test-lefser.R | 12 +++++++++++- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 56ea86f..06c668a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,10 @@ ## Minor improvements and bug fixes +* Fixed `ldaFunction()` adding the signed class-mean difference to the unsigned +LDA coefficient, which shrank or flipped the scores of features enriched in the +reference class; scores no longer depend on the factor level order +(@JamesYang1209, #104) * Updated the vignette to use `mia::convertFromPhyloseq()` in place of the deprecated `mia::makeTreeSummarizedExperimentFromPhyloseq()` (@0xMuluh, #105) diff --git a/R/lefser.R b/R/lefser.R index 6478682..bcbcccd 100644 --- a/R/lefser.R +++ b/R/lefser.R @@ -129,7 +129,9 @@ ldaFunction <- function(data, classes) { ## Feature Importance lda.means.diff <- (lda.fit$means[2, ] - lda.fit$means[1, ]) # difference between the class means for each feature - res <- (lda.means.diff + coeff) / 2 + ## Average the magnitudes as in LEfSe, then sign by the enriched class + ## (negative: first level, positive: second level) + res <- sign(lda.means.diff) * (abs(lda.means.diff) + coeff) / 2 names(res) <- colnames(lda.fit$means) return(res) diff --git a/tests/testthat/test-lefser.R b/tests/testthat/test-lefser.R index 5a593f6..e6f058d 100644 --- a/tests/testthat/test-lefser.R +++ b/tests/testthat/test-lefser.R @@ -121,9 +121,19 @@ test_that("ldaFunction correctly identifies classes and calculates scores", { expect_type(lda_scores, "double") expect_named(lda_scores, c("feature1", "feature2")) + ## feature1 is enriched in the first level (A) and feature2 in the second + ## (B); the two are mirror images, so scores have equal magnitude expect_equal( lda_scores, - c(feature1 = 0, feature2 = 9), + c(feature1 = -9, feature2 = 9), tolerance = 1e-8 ) + + ## Reversing the factor levels flips the sign only (#104) + rev_data <- test_data + rev_data$class <- factor(rev_data$class, levels = c("B", "A")) + rev_scores <- lefser:::ldaFunction( + data = rev_data, classes = levels(rev_data$class) + ) + expect_equal(rev_scores, -lda_scores, tolerance = 1e-8) })