From 46b3d1ed6e2831a42c4cd40d399185a8a72bb029 Mon Sep 17 00:00:00 2001 From: Ven Popov Date: Sun, 31 Mar 2024 04:49:28 +0200 Subject: [PATCH 1/2] add test showing failure of unary '-' --- tests/testthat/test-transformations.R | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/testthat/test-transformations.R b/tests/testthat/test-transformations.R index cf830e2e..46dc7599 100644 --- a/tests/testthat/test-transformations.R +++ b/tests/testthat/test-transformations.R @@ -118,3 +118,14 @@ test_that("inverses are applied automatically", { expect_equal(density(1/(1/dist_gamma(4, 3)), 0.5), density(dist_gamma(4, 3), 0.5)) }) + +test_that("unary negation operator works", { + dist <- dist_normal(1,1) + expect_equal(density(-dist, 0.5), density(dist, -0.5)) + + dist <- dist_wrap('norm', mean = 1) + expect_equal(density(-dist, 0.5), density(dist, -0.5)) + + dist <- dist_student_t(3, mu = 1) + expect_equal(density(-dist, 0.5), density(dist, -0.5)) +}) From 2b8ae5e67adf1eddddf85171e2eba1ccae125c60 Mon Sep 17 00:00:00 2001 From: Ven Popov Date: Sun, 31 Mar 2024 04:55:33 +0200 Subject: [PATCH 2/2] allow unary '-' operator on any distribution --- NEWS.md | 5 +++++ R/default.R | 5 +++++ R/transformed.R | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/NEWS.md b/NEWS.md index 8e26875d..58bb253d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,10 @@ # distributional (development version) +## Bug fixes + +* Fixed error when using '-' as a unary operator on a distribution different from + `dist_normal()` by @venpopov (#95) + # distributional 0.4.0 ## Breaking changes diff --git a/R/default.R b/R/default.R index 15249dd1..b855b437 100755 --- a/R/default.R +++ b/R/default.R @@ -266,6 +266,11 @@ Math.dist_default <- function(x, ...) { #' @method Ops dist_default #' @export Ops.dist_default <- function(e1, e2) { + if(.Generic %in% c("-", "+") && missing(e2)){ + e2 <- e1 + e1 <- if(.Generic == "+") 1 else -1 + .Generic <- "*" + } is_dist <- c(inherits(e1, "dist_default"), inherits(e2, "dist_default")) if(any(vapply(list(e1, e2)[is_dist], dim, numeric(1L)) > 1)){ stop("Transformations of multivariate distributions are not yet supported.") diff --git a/R/transformed.R b/R/transformed.R index aff6c74d..5505e1fa 100755 --- a/R/transformed.R +++ b/R/transformed.R @@ -94,6 +94,11 @@ Math.dist_transformed <- function(x, ...) { #' @method Ops dist_transformed #' @export Ops.dist_transformed <- function(e1, e2) { + if(.Generic %in% c("-", "+") && missing(e2)){ + e2 <- e1 + e1 <- if(.Generic == "+") 1 else -1 + .Generic <- "*" + } is_dist <- c(inherits(e1, "dist_default"), inherits(e2, "dist_default")) trans <- if(all(is_dist)) { if(identical(e1$dist, e2$dist)){