Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow unary negation to work with all distributions #96

Merged
merged 2 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
5 changes: 5 additions & 0 deletions R/default.R
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
5 changes: 5 additions & 0 deletions R/transformed.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)){
Expand Down
11 changes: 11 additions & 0 deletions tests/testthat/test-transformations.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
Loading