1 year ago

#325824

test-img

Leonhard Geisler

Custom renderer in rhandsontable is messing with my numbers format

I am developing a Shiny app with an output tab, that contains a rhandsontable. The numbers in the handsontable should be without decimals and contain a big mark separator in form of a dot: "10.0000" = ten thousand.

However, I experience some difficulties, to achieve the right formatting. In my regex, you can see, I am using a custom renderer to achieve conditional formatting. When you exclude the custom renderer and run the code, I will work as expected. If you execute as indicated, zeros at the end of the numbers will get trimmed.

Maybe there is a smarter approach:

library(tidyverse)

fc_output_tbl <- tibble(`Product ID`  = c(rep("A1",3),rep("A1000",3)),
                        Value = c(6631.98,6770.76,5940.21,2073.45,1896.12,2163),
                        Date = as.Date(rep(c("2015-07-01","2015-08-01","2015-09-01"),2)),
                        `Last year` = c(c(5210,4910,6890,1590,1730,2440))
                        )
fc_output_tbl <- fc_output_tbl %>%
    mutate(`Growth ABS` = Value-abs(`Last year`),
           `Growth PCT` = (Value-abs(`Last year`))/Value) %>% 
    relocate(`Last year`, .after = Value) %>% 
    relocate(`Growth ABS`, .after = `Last year`) %>% 
    relocate(`Growth PCT`, .after = `Growth ABS`) %>% 
    rename(FC = Value) %>% 
    mutate_at(vars(FC,`Growth ABS`
    ), funs(format(round(.,0), nsmall=0, big.mark=".", decimal.mark=" "))
    ) %>% 
    mutate_at(vars(`Last year`
    ), funs(format(as.numeric(`Last year`),trim = FALSE, nsmall=0, big.mark=".", decimal.mark=" "))
    ) 

# tbl
library(rhandsontable)
cell_highlight <- 3:4
rhandsontable(fc_output_tbl, cell_highlight = cell_highlight) %>% 
    hot_cols(renderer = "
              function(instance, td, row, col, prop, value, cellProperties) {
                Handsontable.renderers.NumericRenderer.apply(this, arguments);
                  if (instance.params) {
                    hcols = instance.params.cell_highlight;
                    hcols = hcols instanceof Array ? hcols : [hcols];
                  }
                    if (instance.params &&  hcols.includes(col) && value < 0) {
                      td.style.background = 'pink';
                     } else if (instance.params && hcols.includes(col) && value > 0) {
                      td.style.background = 'lightgreen';
                     }
               }") %>%
    hot_col("Growth PCT", format = "0.0%") 

javascript

r

formatting

rhandsontable

0 Answers

Your Answer

Accepted video resources