From 36d53bc632fd2d29cb2fea4ed74b676200a7aaf1 Mon Sep 17 00:00:00 2001
From: Sebastian Henz <sebastian.henz@ufz.de>
Date: Mon, 4 May 2020 16:24:51 +0200
Subject: [PATCH] Fix error with plot_stress() and which = NULL, fixes #41

---
 NEWS.md         |  1 +
 R/plot_stress.R | 15 +++++++++++++--
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/NEWS.md b/NEWS.md
index 4426786..0d9f1d7 100644
--- a/NEWS.md
+++ b/NEWS.md
@@ -5,6 +5,7 @@
 * Renamed `predict_mixture()` to `multi_tox()`.
 * The argument `proportion_ca` in the mixture model `multi_tox()` was renamed and its value reversed. It is now called `sa_contribution` and specifies the proportion of stress addition in the calculation of toxicant stress. To convert your code from the old version use this equation: sa_contribution = 1 - proportion_ca.
 * Renamed `stress_tox_sam` to `stress_tox_sa` in the output of `multi_tox()`.
+* Fixed a bug where `plot_stress()` with argument `which = NULL` would result in an error. Now it correctly draws the axes without data.
 
 # stressaddition 2.7.0
 
diff --git a/R/plot_stress.R b/R/plot_stress.R
index 9e661d6..8bbd4b2 100644
--- a/R/plot_stress.R
+++ b/R/plot_stress.R
@@ -58,8 +58,19 @@ plot_stress <- function(model,
         model$args$concentration[-1]
     )
 
-    curves_w <- curves[, which[!endsWith(which, "observed")]]
-    ymax <- if (NCOL(curves_w) == 0) 1 else max(curves_w, 1, na.rm = TRUE)
+    if (is.null(which)) {
+        ymax = 1
+    } else {
+        which_lines <- which[!endsWith(which, "observed")]
+        if (length(which_lines) == 0) {
+            ymax <- 1
+        } else {
+            ymax <- max(curves[, which_lines], 1, na.rm = TRUE)
+            # No need to include the observed stress in the call to max() no
+            # matter if those are in "which" or not because these vectors are
+            # clamped to [0, 1] anyway.
+        }
+    }
 
     plot(
         NA,
-- 
GitLab