Search code examples
rdplyrformatnumberstidyverse

Mutate number to 2 decimal places as numeric in R


I have a very simple question that I cannot seem to solve.

How do I change the number 2 to 2.00, as a numeric in my data table with R? Every round(), format(), sprintf(), digit etc. changes the numerical 2 to 2.00 as a character. Same goes for if I wanted one decimal place by changing 2 to 2.0.

Any help would be appreciated thank you.


Solution

  • Here is a way to write a simple class that can perform the task you desire:

    print.my_numbers <- function(x){
      y <- sprintf(sprintf("%%.%df", attr(x, 'after')), x)
      print(y, quote = FALSE)
    }
    
    my_numbers <- function(x, after=0){
      structure(x, after = after, class = 'my_numbers')
    }
    
    d <- my_numbers(1:4, 2)
    d
    [1] 1.00 2.00 3.00 4.00
    d^3
    [1] 1.00  8.00  27.00 64.00
    

    Note that to generalize the use of the class my_numbers you should consider defining the format method for this class