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) })