Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep format width in scientific notation

I'm writing a custom print.xx function to show a bunch of data pretty tabulated. The column width is 11 characters, so I do something like this:

> format(1234.567,width=11,digits=7)
[1] "   1234.567"
> format(1234.56789,width=11,digits=7)
[1] "   1234.568"

So far so good. The problem comes when I have a very large/small number and the scientific notation comes in:

> format(1234.56789e10,width=11,digits=7)
[1] "1.234568e+13"
> format(1234.56789e-10,width=11,digits=7)
[1] "1.234568e-07"

It should use the scientific notation, ok, but I need it to stick to the 11 character width. I've looked up the scientific and scipen parameters, but it still goes beyond the 11 character limit. An option could be to check whether scientific notation is generated, and if so reduce the digits parameter, but looks cheesy to me.

How can I force it to give me a string with a fixed length, regardless of whether the number is in scientific notation or not?

like image 834
Julián Urbano Avatar asked Dec 15 '22 07:12

Julián Urbano


2 Answers

I think you'll have to calculate the digits appropriately.. Something like this, perhaps, will work:

n <- 1234.567e2
prettyNum(n, digits=7-(nchar(n)-11), width=11, format="fg")
# [1] "   123456.7"

n <- 1234.567e9
prettyNum(n, digits=7-(nchar(n)-11), width=11, format="fg")
# [1] "1.23457e+12"

n <- 1234.567e100
prettyNum(n, digits=7-(nchar(n)-11), width=11, format="fg")
# [1] "1.2346e+103"

Or equivalently with format:

format(n, digits=7-(nchar(n)-11), width=11)
like image 157
Arun Avatar answered Dec 31 '22 13:12

Arun


In my case I used:

sprintf("%11.5e",123456789e10)

[1] "1.23457e+18"

You just need to know how many characters you want and do the right balance between width.decimal, that is %11.5e

like image 24
Aliton Oliveira Avatar answered Dec 31 '22 14:12

Aliton Oliveira