"Efficiently calculate the total sum of columns in a datatable using dynamic JavaScript across

For further clarification, this question is an extension of a previous inquiry, which can be viewed here.

In the following code snippet, I am calculating the column sum of a Shiny datatable using Javascript in order to display it directly below the table.

library(shiny)
library(DT)

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

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

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))
  
  opts <- list(
    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/eE48s.png

One point to note is that sorting the table will alter the column sum, as the total only represents the displayed column. My goal is to modify this so that it reflects the overall sum when dealing with multiple "pages" of the table, while still maintaining the current functionality for single-page scenarios.

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

Answer №1

Setting server to FALSE in renderDT and including column(5, {search: 'applied'}) in the JavaScript:

library(shiny)
library(DT)

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

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

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))
  
  opts <- list(
    footerCallback = JS(
      "function(tfoot, data, start, end, display){
      var api = this.api(), data;
      var sum1 = api.column(5, {search: 'applied'}).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 <- renderDT({
    datatable(
      mtcars, 
      container = sketch, 
      extensions = "Buttons", 
      options = opts
    )
  }, server = FALSE)
}

shinyApp(ui = ui, server = server)

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

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. https://i.sstatic.net/0kFJw.png https://i.sstatic.net/S20cS.png I had it working previously, but unsure when it stopped ...

I'm facing an issue with SSRProvider in my NextJs application

My application is developed using NextJs and Typescript, utilizing the react-bootstrap library for creating components. I am facing an issue where I keep receiving an error message stating that When server rendering, you must wrap your application in an &l ...

AngularJS - sorting JSON data based on key values

I am working with a JSON data set that I need to filter based on the selected option value. The select input is bound to an ng-model, but for some reason, the filter isn't functioning properly. Can anyone spot what mistake I might be making? This is ...

Creating a URL using input fields with JavaScript or jQuery

I'm currently working on developing a form that acts as a URL builder using JavaScript or jQuery. The main concept behind this form is to take the user-input values from two fields, combine them with a preset URL structure, and display the resulting ...

An issue arose when attempting to compute the gradient of a function that was imported from R using the

I am currently tackling a challenge where I am utilizing Tensorflow probability optimizers in Python to solve an optimization problem that I have previously defined in R. These are the steps I am following: Step 1: Defining the original Python problem to ...

Vue.js: Retrieving and Using Data from the API Repeatedly

<template> <h1 class="text-lg text-gray-400 font-medium">Tracker dashboard</h1> <div class="flex flex-col mt-2 w-3/4"> <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> ...

Pull out the educational degree using str_match_all in R programming language

Looking to extract degree information from an R string column containing education details, and then create categorical variables indicating undergraduate or graduate degrees (undergrad.dummy and grad.dummy). df = data.frame(educ = c("Angelo State Uni ...

Find the names of columns that meet a specific condition by comparing them to another column

I am working with a dataframe that looks like this: df <- data.frame( Death = as.Date(c("2017-09-20")), First_Date = as.Date(c("2016-09-09", "2018-09-20", "2016-09-09")), Second_Date = as.Date(c("2019-05 ...

Tips for using the useState hook to modify an array by its index?

I am working on a select component that needs to update values in an array of objects based on the index. Utilizing the hook as follows: const [areas, setAreas] = useState(product.areas); This is how the "areas" array looks: [ 0: {de: "Getraenke", en: ...

Issue encountered: Unable to locate module: Error - Unable to resolve '@cycle/run' with webpack version 2.2.1

I am attempting to run a hello world application using cycle.js with webpack 2.2.1. The following error is being displayed: ERROR in ./app/index.js Module not found: Error: Can't resolve '@cycle/run' in '/Users/Ben/proj/sb_vol_cal ...

Implementing Vuetify 3 and vue-i18n for the tag attribute

When looking to include localized text within tag content, I typically use the following method: <span>{{ $t('myText') }}</span> However, I have been unable to find a way to add localized text for tag attributes. I attempted the foll ...

creating an array of piecharts with varying sizes in raphaeljs

I have a task to visually represent the voting results stored in a MySQL database. Each question in the database has corresponding answers, with each answer containing 5 numerical values. The list below shows the questions and their respective answers: Q1 ...

Displaying a pop-up message using JavaScript: How to trigger it with jQuery

Within my application, I have successfully implemented a basic JavaScript popup by invoking it in this manner- <a href="javascript:popup('Hello World')>Click Me</a> I am curious if it is feasible to trigger the same popup using othe ...

Issue with php and ajax causing loop malfunction

I'm currently working on building a simple USD to pounds converter using PHP and AJAX. While I know it would be simpler with jQuery, unfortunately, the use of jQuery is not allowed for this assignment. The problem I'm facing is that when I run th ...

What steps should I take to address the issue of sanitizing a potentially harmful URL value that contains a

I've encountered a URL sanitization error in Angular and despite researching various solutions, I have been unable to implement any of them successfully in my specific case. Hence, I am reaching out for assistance. Below is the function causing the i ...

I am having trouble getting the unix timestamp to work with Meteor's API, pickadate.js

Based on the information from the API at , I have implemented the following code to retrieve a Unix timestamp based on a selected date. Initially, I configured: $('.startDate').pickadate({ selectMonths: true, selectYears: 15 ...

Leveraging R for generating visual representations of numeric data

Here are some numbers I have: 170,295,200,165,140,190,195,142,138,148,110,140,103,176,125,126,204,196,98,123,124 152,177,168,175,186,140,147,174,155,195 I want to create a histogram using R with these numbers. Should I organize them in an array first? I ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

"Data passed to a JavaScript callback function may result in an undefined

I've been experiencing some issues with callbacks and getting return data as undefined. function goodMorning(name, msg) { return `${name} ${msg}`; } function greet(name, msg, cb) { const myName = "Sairam"; console.log(`${cb(name)} ${cb(msg)} ...

Shortening extensive R output in knitr

I recall coming across a method in knitr to shorten R output, but the details have slipped my mind. How can I display the first few lines and last few lines of R output with an ellipses (...) in between? \documentclass{article} \begin{doc ...