block by timelyportfolio 8921acd5236418278b5899e14745788c

rhandsontable widget with JavaScript calc

Full Screen

handsontable pro version allows formula-based cells similar to Excel. With the R htmlwidget rhandsontable we might want similar functionality with the calculations staying within JavaScript. Here is a very simple example to make a totals row.

library(rhandsontable)

# create some quick data to test and append a row for totals
dat <- rbind(
  head(mtcars,10),
  # sum doesn't really make sense for the total but use
  #  in this example as an aggregate function
  lapply(head(mtcars,10), sum)
)
rownames(dat)[11] <- "Totals"

rht <- rhandsontable(dat) %>%
  # make totals row readOnly to prevent user from overwriting
  hot_row(11, readOnly = TRUE)

htmlwidgets::onRender(
  rht,
"
function(el, x) {
  var hot = this.hot
  hot.addHook(
    'afterChange',
    function(changes, source) {
      if(source === 'edit') {
        //debugger
        changes.forEach(function(change) {
          var sum = hot.getData(0,change[1],9,change[1]).map(
              function(d){ return parseFloat(d[0]) || 0 }
            ).reduce(
            // simple reduce to calculate sum
            function(left,right) {
              return left + right
            },
            0
          )
          hot.setDataAtCell(10, change[1], sum, 'calculate') // make sure to specify 'calculate' so no infinte loop
        })
      }
    }
  )
}
"
)