Search code examples
rhtml-tabledecimalseparator

create function my.render.cat with comma decimal separator instead of point in r


I am trying to create a function to get frequencies and proportions for a table1 with this code

my.render.cat <- function(x) { c("", sapply(stats.default(x), function(y) with(y, sprintf("%d (%0.0f %%)", FREQ, PCT)))) }

but when I apply it to the function table1() I get the results for proportions with decimal point instead of comma.

I've tried with options(OutDec= ",") but nothing changes Nor by changing Sys.locale for LC NUMERIC.

I've also tried with format(table1, decimal.mark=",") but it doesn't work for table1 output

any suggestions?

I add a reproducible example using iris dataset and formatting Sepal.length to be able to calculate proportions.

table1::table1(~factor(Sepal.Length) | Species, data = iris, render.categorical=my.render.cat)


Solution

  • You can use sub to replace . with ,.

    library(table1)
    
    my.render.cat <- function(x) { 
      sub('.', ',', c("", sapply(stats.default(x), 
      function(y) with(y, sprintf("%d (%0.2f %%)", FREQ, PCT)))), fixed = TRUE) 
    }
    
    table1(~factor(Sepal.Length) | Species, data = iris, 
           render.categorical=my.render.cat)