Home > Net >  Make adjustments to output table that has numbers
Make adjustments to output table that has numbers

Time:01-06

How do I make an output table to have numeric values formatted, for example, to be 445,23, instead of US$445.23. That is, I would need to withdraw US$ and instead of having a point(.), let it be a comma.

Test <- structure(list(date2 = structure(c(18808, 18808, 18809, 18810
), class = "Date"), Category = c("FDE", "ABC", "FDE", "ABC"), 
coef1 = c(445.23231, 1.31231, 6.32323, 1.232),coef2 = c(8.3231, 3.3432, 1.3233, 6.3233)), row.names = c(NA, 4L), class = "data.frame")

Test %>%
  mutate(sum = rowSums(across(3:last_col()), na.rm = TRUE), 
         across(where(is.numeric), ~sprintf("US $%,2f", .x)))

CodePudding user response:

The , wouldn't work for the sprintf with f. According to ?sprintf

f - Double precision value, in “fixed point” decimal notation of the form "[-]mmm.ddd". The number of decimal places ("d") is specified by the precision: the default is 6; a precision of 0 suppresses the decimal point. Non-finite values are converted to NA, NaN or (perhaps a sign followed by) Inf.

We may need to change the . to , later with sub (from base R) or str_replace (from stringr)

library(dplyr)
Test %>%
   mutate(sum = rowSums(across(3:last_col()), na.rm = TRUE), 
   across(where(is.numeric), ~ sub(".", ",", 
       sprintf("%0.2f", .x), fixed = TRUE)))
          date2 Category  coef1 coef2    sum
1 2021-06-30      FDE 445,23  8,32 453,56
2 2021-06-30      ABC   1,31  3,34   4,66
3 2021-07-01      FDE   6,32  1,32   7,65
4 2021-07-02      ABC   1,23  6,32   7,56

CodePudding user response:

You can tell sprintf to use , as the decimal separator by setting an appropriate numeric formatting locale. However, the way in which this is set matters — you can’t use Sys.setenv, you need to use Sys.setlocale instead. For instance:

Sys.setlocale('LC_NUMERIC', 'de_DE')

Afterwards, your code (but using the correct format string!, i.e. ~sprintf("US $%.2f", .x)) does what you want.

  •  Tags:  
  • Related