Hanjo Odendaal
Hanjo Odendaal

Reputation: 1441

Formattable breaks column sort in DataTable in Shiny

I am currently creating a small dashboard using flexdashboard and shiny. It contains a lot of accounting columns where it is essential to be able to sort the values. As part of the table I use the formattable library to format the columns to accounting before I render the table.

The problem is that the formatted columns break the sorting of DataTable as formattable essentially converts the numeric to text.

Here is code to reproduce the issue:

---
title: "Dashboard"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
runtime: shiny
---

```{r packages, include = F}
library(DT)
library(formattable)
library(dplyr)
```

```{r}
sign_formatter <- formattable::formatter("span", 
                                         style = x ~ style(color = ifelse(x > 0, "green", 
                                                                          ifelse(x < 0, "red", "black"))))
```

Results {data-height=800 data-width=100%}
---------------------------------------------

```{r data}
df <- data.frame(category = sample(LETTERS, 30, replace = T), 
                 income = runif(30, -10, 10) * 1e4)

# Format Table
df <- df %>%
  mutate(`income` = accounting(`income`, digits = 0L))

renderDataTable(
  formattable(df, list(
     `income` = sign_formatter
    )) %>%
    as.datatable(., class = 'cell-border stripe table table-striped',
                 filter = 'top', escape = FALSE, selection = 'none',
                 options = list(autoWidth = TRUE,
                                server = TRUE,
                                fixedHeader = TRUE,
                                columnDefs = list(list(width = '200px', targets = c(1)))
                                ), rownames = FALSE)
  )

```

The small picture below illustrates the problem when I sort desceding:

example

Upvotes: 4

Views: 917

Answers (0)

Related Questions