Revise shiny datatable to display total column sum differently

This is a follow up question to this inquiry: Adding Total/Subtotal to the bottom of a DataTable in Shiny. Below is the code snippet referenced:

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1('Testing TableTools'),
  mainPanel(
    dataTableOutput('display')
  )      
))

Names <- c("",names(mtcars))
FooterNames <- c(rep("",4),Names[5:6],rep("",6))

server <- function(input, output, session) {

  sketch <- htmltools::withTags(table(
    tableHeader(Names),tableFooter(FooterNames)
  ))

  opts <- list(
    dom = 'Bfrtip', buttons = list('colvis','print',list(extend='collection',text='Download',buttons = list('copy','csv','excel','pdf'))),
               footerCallback = JS(
                 "function( tfoot, data, start, end, display ) {",
                 "var api = this.api(), data;",
                 "$( api.column(5).footer()).html('SubTotal:  '+",
                 "api.column(5).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");",
                 "$( api.column(4).footer()).html('SubTotal: '+",
                 "api.column(4).data().reduce( function ( a, b ) {",
                 "return a + b;",
                 "} )",
                 ");","}")
  )

  output$display <- DT::renderDataTable(container = sketch,extensions = 'Buttons',options = opts,{
    mtcars
  })
}

shinyApp(ui = ui, server = server)

When displaying subTotal in the dataframe, it presents the numbers with more than two digits after the decimal point, such as 1234,51999999999 instead of 1234,52.

To rectify this issue, what changes need to be made in the Javascript code to only display two digits after the decimal point, use a dot as a thousands separator, a comma as a decimal point, and also include a Euro (€) symbol next to the sum?

Answer №1

Why use JavaScript with shiny when you can achieve the same in R? Here's the R way:

paste0(
  formatC(1234.51999999999, format="f", big.mark=".",
  decimal.mark = ",", digits=2), "€"
)
# [1] "1.234,52€"

Alternatively, you can use JS to accomplish the task:

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1("Testing TableTools"),
  mainPanel(
    dataTableOutput("display")
  )
))

Names <- c("", names(mtcars))
FooterNames <- c(rep("", 4), Names[5:6], rep("", 6))

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))

  opts <- list(
    dom = "Bfrtip", buttons = list("colvis", "print", list(extend = "collection", text = "Download", buttons = list("copy", "csv", "excel", "pdf"))),
    footerCallback = JS(
      "
      function(tfoot, data, start, end, display) {
    var api = this.api(),
        data;
    var sum1 =  api.column(5).data().reduce(function(a, b) {
        return a + b;
    });
    sum1 = Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(sum1)

    $(api.column(5).footer()).html('SubTotal:  ' + sum1)
}
"
    )
  )

  output$display <- DT::renderDataTable(container = sketch, extensions = "Buttons", options = opts, {
    mtcars
  })
}

shinyApp(ui = ui, server = server)

https://i.sstatic.net/FriW4.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve all references to child elements in React

I am working on a component that renders dynamic children, and I need to assign a unique ref to each child (e.g. ref={'childID' + index}) After the children have been loaded, I am looking for a way to loop through them and access their refs. Is ...

The contents of the image are currently unable to be viewed

I have a Blob of an image that I am trying to display in the browser. However, when I use the code below to open the image, it shows some Mandarin scripts on the window. Here is the code snippet: var url="http://....link..../downloadFile?fdsFileId="+file ...

How to implement the Ionic ToastController without being confined to a Vue instance

I am currently facing a challenge while trying to utilize the ToastController of Ionic outside a vue instance. I have created a separate actions file which will be loaded within the vue instance, handling a request. Within this request, certain validations ...

How can I obtain the true client IP address using Nginx?

I have a straightforward express app that has been containerized using Docker. You can find the repository here. In this setup, I utilized nginx as a reverse proxy. When accessing http://45.33.97.232:3000, it displays the actual server IP. However, if I v ...

A guide on resolving the 'Unexpected identifier array in JSON Parse Error' encountered during an AJAX Request

I'm currently working on setting up a Contact Form Validation and I require the variable $msg from a php script called 'sendEmail.php'. The actual mailing system is functional, as the script successfully receives form inputs from index.php a ...

Issues with jQuery AJAX functionality

I am in the process of incorporating some ajax functionality into my php website. I have a good understanding of jQuery, but for some reason, the value returned is always empty when I try to alert() it. Below is the code snippet that I am using: PHP: if( ...

Redirect link depending on JSON callback information

I experimented with utilizing JavaScript to automatically redirect website visitors based on their country. The code snippet below demonstrates how the visitor's IP is checked to determine their country, such as CN for China, and then redirects them ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

Tips for removing the default hover and click effects from a Material-UI CardActionArea

Check out the card sample with a lizard photo on https://material-ui.com/components/cards. When you hover over the cardActionArea, it will get darker or lighter based on the theme. Clicking on the card will make the picture change its brightness relative ...

Implementing functions on React component classes

Recently, I decided to convert a slideshow from w3s schools into a React component. The process involved changing all the functions into methods on the class and setting the initial state to display the first slide. However, upon clicking the buttons or do ...

Managing reverted MySQL transactions in a Node.js environment

I've been struggling with an issue for a few days now and I'm really hoping that you could provide some assistance. The problem lies in a node.js API using sequelize to interact with a MySQL database. When certain API calls are made, the code i ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

Verifying if a particular track is currently playing in the HowlerJS playlist

I am currently experimenting with a HowlerJS playlist code and would like to create a button that can detect if a specific song in the playlist is playing. When this button is clicked, I want it to hide a certain line of text. However, my knowledge on this ...

Create directories in a nested structure using a multi-level JSON object with async.js

DEFINITION NewMethod#generateDirectoriesFromJSON (data, cb); data: JSON object. cb: Callback function. Parameters: err (Error), directoriesCreated (Boolean, true if at least one directory has been created). Assuming that the NewMethod class includes a ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

ReactJS aligns buttons to the right

I have been attempting to align a button to the far right without success. Here is what I have tried: <Button variant="contained" style={{display: 'flex', justifyContent: 'right'}} color="primary" className="float-right" onClick={ ...

Strange behavior occurs when a DOCTYPE is specified in XSLT and javascript interactions

Within our XLST, we utilize "vanilla" JavaScript to manipulate certain div elements within our reports. One particular div sits in the center of the screen and overlaps all other content. The code snippet below is used to position this div when the page lo ...

If I type too quickly in the input field, it ends up displaying the incorrect div

I need to display two different dropdowns in my input field. To achieve this, I am using a method called shouldShowWarningBox that gets triggered every time the user updates the input and updates the value of showWarningBox accordingly. However, when I typ ...