How to format a variable with commas, now that scales has changed

In the previous version of scales there was a function comma() that could be used to format a number using commas as separators. However, in 1.1.0 comma() is deprecated and it seems like the suggested replacements are things like label_comma(). I don't see vignettes for scales, and the example code in the function documentation is pretty opaque to me, but it seems like label_comma() is just for use within a ggplot2 scale_ function. What should I use to generically format a variable with commas?

library(scales)
library(dplyr)

df <- tibble(prem = c(1000.51, 1000.4, 10, 17))

df <- df %>%
  mutate(prem_formatted = label_comma(prem))
#> Error: Column `prem_formatted` is of unsupported type function

Created on 2020-03-12 by the reprex package (v0.3.0)

3 Likes

I think you can use number().

library(scales)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- tibble(prem = c(1000.51, 1000.4, 10, 17))

df %>%
  mutate(prem_formatted = number(prem, big.mark = ","))
#> # A tibble: 4 x 2
#>    prem prem_formatted
#>   <dbl> <chr>         
#> 1 1001. 1,000.51      
#> 2 1000. 1,000.40      
#> 3   10  10.00         
#> 4   17  17.00

Created on 2020-03-12 by the reprex package (v0.3.0)

label_comma returns a function, so the code below would work, but it's cumbersome and not really intended to be used that way.

df <- df %>%
  mutate(prem_formatted = label_comma()(prem))

In addition to siddharthprabhu's suggestion, you could also use the base format function, which works similarly (format(prem, big.mark=",")).

1 Like

Hey Amelia,

This sounds like it would be a good documentation request for the scales package. Would you mind filing an issue there?


Or, if you prefer, I'm happy to bring this over there for you.

I feel like the past two release announcements for scales could be reshaped into vignettes, and we could definitely do a better job of linking the relevant info from the ggplot2 docs.


Thanks for bringing this up!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.