Skip to content

Prompt users about pillar::num() for customising the rounding of numbers #913

@charliejhadley

Description

@charliejhadley

The {pillar} package has recently introduced num() to aid in customising how {tibble} prints rounded numbers.

There have been a few issues requesting this feature, I originally opened r-lib/pillar#97 which includes both a reprex and suggested fix r-lib/pillar#97 (comment)

It's difficult to tell {pillar} not to round numbers straddling 0 - 1

library("tidyverse")
#> ── Attaching packages ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 2.2.1     ✔ purrr   0.2.4
#> ✔ tibble  1.4.2     ✔ dplyr   0.7.4
#> ✔ tidyr   0.8.0     ✔ stringr 1.2.0
#> ✔ readr   1.1.1     ✔ forcats 0.2.0
#> ── Conflicts ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
my_numbers <-  c(233, 486, 565, 785)
straddle_data <- tibble(
  big = 1000 * my_numbers + 23,
  stradle = my_numbers / 1000 + 100,
  small = my_numbers / 100000
)
straddle_data
#> # A tibble: 4 x 3
#>      big straddle   small
#>    <dbl>   <dbl>   <dbl>
#> 1 233023     100 0.00233
#> 2 486023     100 0.00486
#> 3 565023     101 0.00565
#> 4 785023     101 0.00785

Which is now controllable with

library(pillar)

extra_digits <- function(x) {
  x <- sort(abs(x))
  delta <- diff(x)
  x <- x[-1]

  keep <- which((delta != 0) & is.finite(delta))
  if (length(keep) == 0) {
    return(0)
  }

  x <- x[keep]
  delta <- delta[keep]

  ceiling(log10(max(x / delta)))
}

num_with_extra_digits <- function(x) {
  num(x, sigfig = 3 + extra_digits(x))
}

my_numbers <- c(233, 486, 565, 785)

tibble::tibble(
  big = num_with_extra_digits(1000 * my_numbers + 23),
  straddle = num_with_extra_digits(my_numbers / 1000 + 100),
  straddle2 = num_with_extra_digits(my_numbers / 1000 + 1000),
  straddle3 = num_with_extra_digits(my_numbers / 10000 + 10000),
  small = num_with_extra_digits(my_numbers / 100000)
)
#> # A tibble: 4 × 5
#>       big straddle straddle2  straddle3   small
#>   <num:4>  <num:7>   <num:8>   <num:10> <num:4>
#> 1  233023  100.233  1000.233 10000.0233 0.00233
#> 2  486023  100.486  1000.486 10000.0486 0.00486
#> 3  565023  100.565  1000.565 10000.0565 0.00565
#> 4  785023  100.785  1000.785 10000.0785 0.00785

I feel it would be useful for {tibble} to make users aware of the num() functionality.

Would it be possible to print a message to users on a once per session basis, specifically if {pillar} trims a number like 100.233 to 100. ?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions