Skip to content

Commit

Permalink
better fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Melkiades committed Feb 21, 2024
1 parent f395712 commit eca8ba9
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 3 deletions.
2 changes: 1 addition & 1 deletion R/formatting_functions.R
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ format_count_fraction_fixed_dp <- function(x, ...) {

result <- if (x[1] == 0) {
"0"
} else if (all.equal(x[2], 1)) {
} else if (.is_equal_float(x[2], 1)) {
sprintf("%d (100%%)", x[1])
} else {
sprintf("%d (%.1f%%)", x[1], x[2] * 100)
Expand Down
26 changes: 25 additions & 1 deletion R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,36 @@ check_same_n <- function(..., omit_null = TRUE) {

if (length(unique(n)) > 1) {
sel <- which(n != n[1])
stop("dimension mismatch:", paste(names(n)[sel], collapse = ", "), " do not have N=", n[1])
stop("Dimension mismatch:", paste(names(n)[sel], collapse = ", "), " do not have N=", n[1])
}

TRUE
}

#' Utility function to check if a float is equal to another float
#'
#' @description Uses `.Machine$double.eps` as the tolerance for the comparison.
#'
#' @param x (`float`)\cr A single number.
#' @param y (`float`)\cr A single number.
#'
#' @return `TRUE`, if identical. `FALSE`, otherwise
#'
#' @examples
#' .is_equal_float(49/49, 1)
#'
#' @keywords internal
.is_equal_float <- function(x, y) {
checkmate::assert_number(x)
checkmate::assert_number(y)

# Define a tolerance
tolerance <- .Machine$double.eps

# Check if x is close enough to y
abs(x - y) < tolerance
}

#' Make Names Without Dots
#'
#' @param nams (`character`)\cr vector of original names.
Expand Down
24 changes: 24 additions & 0 deletions man/dot-is_equal_float.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tests/testthat/test-formats.R
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ testthat::test_that("formats with nominator == to denominator are always formatt
rowwise() %>%
mutate(count = Ncol) %>%
mutate(pct = count * (1 / Ncol)) %>%
mutate(check_new = all.equal(pct, 1)) %>%
mutate(check_new = .is_equal_float(pct, 1)) %>%
mutate(check = pct == 1) %>%
mutate(fmt_print = format_count_fraction_fixed_dp(c(count, pct)))

Expand Down

0 comments on commit eca8ba9

Please sign in to comment.