From 97c881008b736e7513cf3f30b8fb8f65f9a64f06 Mon Sep 17 00:00:00 2001 From: js2264 Date: Wed, 10 Jan 2024 14:36:16 +0100 Subject: [PATCH] fix: as.matrix returns sparse by default, use as(x, 'dgTMatrix') for sparse --- R/coerce.R | 10 +++++++++- man/as.Rd | 2 +- tests/testthat/test-HiCExperiment-methods.R | 16 +++++++++++++--- vignettes/HiCExperiment.Rmd | 3 ++- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/R/coerce.R b/R/coerce.R index 6ee69ff..827c96f 100644 --- a/R/coerce.R +++ b/R/coerce.R @@ -90,6 +90,14 @@ setAs("HiCExperiment", "ContactMatrix", function(from) { #' @name as setAs("HiCExperiment", "matrix", function(from) { + as(from, "ContactMatrix") |> cm2matrix(sparse = FALSE) +}) + + +#' @export +#' @name as + +setAs("HiCExperiment", "dgTMatrix", function(from) { as(from, "ContactMatrix") |> cm2matrix(sparse = TRUE) }) @@ -109,7 +117,7 @@ setAs("HiCExperiment", "data.frame", function(from) { #' @export #' @name as -setMethod("as.matrix", "HiCExperiment", function(x, use.scores = "balanced", sparse = TRUE) { +setMethod("as.matrix", "HiCExperiment", function(x, use.scores = "balanced", sparse = FALSE) { interactions(x) |> gi2cm(use.scores = use.scores) |> cm2matrix(sparse = sparse) }) diff --git a/man/as.Rd b/man/as.Rd index 8ab49e8..30057d5 100644 --- a/man/as.Rd +++ b/man/as.Rd @@ -14,7 +14,7 @@ \alias{df2gi} \title{Coercing functions} \usage{ -\S4method{as.matrix}{HiCExperiment}(x, use.scores = "balanced", sparse = TRUE) +\S4method{as.matrix}{HiCExperiment}(x, use.scores = "balanced", sparse = FALSE) \S4method{as.data.frame}{HiCExperiment}(x) diff --git a/tests/testthat/test-HiCExperiment-methods.R b/tests/testthat/test-HiCExperiment-methods.R index 8bac85a..28b0c33 100644 --- a/tests/testthat/test-HiCExperiment-methods.R +++ b/tests/testthat/test-HiCExperiment-methods.R @@ -95,13 +95,23 @@ test_that("coerce works", { expect_s4_class({ as(contacts_yeast, 'ContactMatrix') }, 'ContactMatrix') - expect_true(is.matrix(base::as.matrix(as.matrix(contacts_yeast)))) + expect_true({ + is.matrix(as(contacts_yeast, 'matrix')) + }) + expect_false({ + is.matrix(as(contacts_yeast, 'dgTMatrix')) + }) expect_s4_class({ - as(contacts_yeast, 'matrix') + as(contacts_yeast, 'dgTMatrix') }, 'dgTMatrix') expect_s4_class({ - as.matrix(contacts_yeast) + as.matrix(contacts_yeast, sparse = TRUE) }, 'dgTMatrix') + expect_true({ + is.matrix( + as.matrix(contacts_yeast, sparse = FALSE) + ) + }) expect_s3_class({ df <- as(contacts_yeast, 'data.frame') }, 'data.frame') diff --git a/vignettes/HiCExperiment.Rmd b/vignettes/HiCExperiment.Rmd index 898e92a..520654b 100644 --- a/vignettes/HiCExperiment.Rmd +++ b/vignettes/HiCExperiment.Rmd @@ -116,8 +116,9 @@ The implemented `import()` methods allow one to import Hi-C matrix files in R as `HiCExperiment` objects. ```{r import, eval = FALSE} +## Change .cool accordingly hic <- import( - "path/to/contact_matrix.cool", + ".cool", focus = "chr:start-end", resolution = ... )