Quick demo and explanation below!
First, why? I’m working on an image-driven dashboard which users can sort by the value represented in the plot. We’ll share more about that soon - the short story is that I’m creating character-sortable strings containing the value using str_pad()
to make the all the same width.
So, what’s going on?
The answer is default scientific formatting behind the scenes!
Good to know!
How do we avoid that?
You can switch off scientific formatting in your options()
, but if you don’t want to do that, just use format(x, scientific = F)
.
A tad convoluted, but it did the job I needed within the constraints of the project!
What did others suggest?
For what it’s worth, str_length()
has the same behaviour. And this also isn’t the safest long term solution because it is based on how the numbers are printed rather than on the numbers themselves. It just did the trick within the constraints of the project (i.e. I knew the max number wouldn’t break this solution).
When I shared this on Twitter, the best solution came from Hadley Wickham (thank you Hadley!):
I’d suggest using
sprintf()
instead — it’s designed specifically for the use case of padding numbers.str_pad()
would also break here if you ever get a non integer
When I asked how I would make sure it would pad to the same nchar as the longest integer in the data, here was his suggestion:
You can figure that out with something like
floor(max(log10(x)))