3

I'm building a shiny app in R, one of the outputs of which is a table with summary data. The values appearing in this table are very variable - from 0.003 to 3,450,023.

I would like to have a way in which I can format the numbers for display so that, for example, numbers less than 0 are always displayed with three decimal places, numbers between 0 and 10 get one decimal place and everything else gets no decimal place at all, simply to make it easier for the user to read the data.

I've looked at this question which fixes the number of decimal places, which is not what I want. I've also played with signif which restricts the number of digits, leading to scientific notation of large numbers which is not suitable for the audience.

Before I go and build a little function to sort this out for me, is there a built-in way to do this in R?

Hester Lyons
  • 803
  • 11
  • 24
  • You know about `sprintf`, `formatC` and `prettyNum`? If none of those work then you probably should write your own function. –  Apr 06 '18 at 09:27
  • Yes I am familiar with all of them but they won't return quite what I want in one call. I've ended up writing a function pretty much like the one below. Thanks. – Hester Lyons Apr 06 '18 at 12:59

1 Answers1

2

Probably There has no Format function in R which works at a time based on different conditions. You can apply format function based on this condition :

           number <-function(number){
           if(number<0){
           result <- format(number,nsmall = 3)
           }else if(number %in% 0:10){
           result <-  format(number , nsmall = 1)
           }else{
           result <- format(number , nsmall=0)
           }
           return(result)
           }
Sorif Hossain
  • 1,231
  • 1
  • 11
  • 18