total=0: error due to ratio = NaN
HenrikBengtsson opened this issue · 0 comments
HenrikBengtsson commented
Issue
library(progress)
pb <- progress_bar$new(total = 0L, show_after = 0.0)
dummy <- pb$tick(0)
# Error in rep("", complete_len) : invalid 'times' argument
Troubleshooting
> traceback()
5: paste(rep("", complete_len), collapse = private$chars$complete)
4: pb_render(self, private, tokens)
3: private$render(tokens)
2: pb_tick(self, private, len, tokens)
1: pb$tick(0)
This happens because pb_ratio()
returns NaN
(as also pointed out in #111 and #79)
> progress:::pb_ratio
function (self, private)
{
ratio <- (private$current/private$total)
ratio <- max(ratio, 0)
ratio <- min(ratio, 1)
ratio
}
Patch
A patch would be:
index d72da62..d11fc20 100644
--- a/R/progress.R
+++ b/R/progress.R
@@ -318,8 +318,8 @@ pb_tick <- function(self, private, len, tokens) {
pb_ratio <- function(self, private) {
ratio <- (private$current / private$total)
- ratio <- max(ratio, 0)
- ratio <- min(ratio, 1)
+ ratio <- max(c(ratio, 0), na.rm = TRUE)
+ ratio <- min(c(ratio, 1), na.rm = TRUE)
ratio
}
Session info
> sessionInfo()
R version 4.0.4 (2021-02-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.5 LTS
Matrix products: default
BLAS: /home/hb/shared/software/CBI/R-4.0.4/lib/R/lib/libRblas.so
LAPACK: /home/hb/shared/software/CBI/R-4.0.4/lib/R/lib/libRlapack.so
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] progress_1.2.2.9000
loaded via a namespace (and not attached):
[1] compiler_4.0.4 ellipsis_0.3.1 R6_2.5.0 hms_1.0.0
[5] prettyunits_1.1.1 crayon_1.4.1 vctrs_0.3.7 lifecycle_1.0.0
[9] pkgconfig_2.0.3 rlang_0.4.10
Background
It's useful to be able to create zero-length progress bars. This way one could do:
my_apply <- function(X) {
pb <- progress_bar$new(total = length(X))
on.exit(pb$terminate())
lapply(X, FUN = function(x) {
pb$tick()
sqrt(x)
})
}
without having to condition the code on length(X) == 0
.
See also
This is related to #79 ('Segfault when total=0') and probably also to #111 ('Error when total = NA and format contains :bar'). However, since #79 is on native code and segfault, and my example is a pure R problem, I decided to post it as a standalone issue