Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

Format numbers to significant figures nicely in R

I want to format numbers in my reports to significant digits, but keep trailing significant zeroes and correctly format large numbers

For instance the numbers c(10.00001,12345,1234.5,123.45,1.2345,0.12345) to 3 significant digits should be 10.0, 12300, 1230, 123, 1.23, 0.123 but I get differing results with different methods (and none seem to work universaly.

> numbers<-c(10.00001,12345,1234.5,123.45,1.2345,0.12345)
> for(n in seq(numbers)){
+   print(signif(numbers[n],digits=3))
+   print(format(numbers[n],digits=3))
+   print(formatC(numbers[n], digits=3,format="fg"))
+   print(formatC(numbers[n], digits=3,format="fg", flag="#"))
+   }
[1] 10
[1] "10"
[1] "  10"
[1] "10.0"
[1] 12300
[1] "12345"
[1] "12345"
[1] "12345."
[1] 1230
[1] "1234"
[1] "1234"
[1] "1234."
[1] 123
[1] "123"
[1] " 123"
[1] "123."
[1] 12.3
[1] "12.3"
[1] "12.3"
[1] "12.3"
[1] 1.23
[1] "1.23"
[1] "1.23"
[1] "1.23"
[1] 0.123
[1] "0.123"
[1] "0.123"
[1] "0.123"

Here, signif and format round the 10.00001 result. formatC with flag="#" correctly does the small numbers but not the large numbers.

Is there a better way ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sorry I never updated this at the time. None of the statements in my question, or prettynum worked. In the end I used

print(formatC(signif(numbers[n],digits=3), digits=3,format="fg", flag="#"))

which correctly coped with trailing zero's and big numbers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...