Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve row order of rhandsontable in shiny app

Tags:

r

shiny

I am running an example from here.

library(rhandsontable)
library(shiny)

runApp(shinyApp(
  ui = fluidPage(rHandsontableOutput("hot")),
  server = function(input, output, session) {
    fname <- "mtcars2.csv"
    values <- reactiveValues()
    setHot <- function(x) values[["hot"]] = x

    observe({
      if(!is.null(values[["hot"]])) write.csv(values[["hot"]], fname)
    })

    output$hot <- renderRHandsontable({
      if (!is.null(input$hot)) {
        DF <- hot_to_r(input$hot)
      } else {
        DF <- read.csv("mtcars.csv", stringsAsFactors = FALSE)
      }
      setHot(DF)
      rhandsontable(DF) %>%
        hot_table(highlightCol = TRUE, highlightRow = TRUE) %>%
        hot_cols(columnSorting = TRUE)
    })
  }
))

I want changes made to table be saved in file mtcars2.csv. I also want to preserve row order. In project home page it says "sorting only impacts the widget and will not reorder the original data set". Can I somehow get current view of a table and save it?

like image 341
danas.zuokas Avatar asked Oct 31 '22 07:10

danas.zuokas


1 Answers

The best way to answer this question will be to file an issue at https://github.com/jrowen/rhandsontable. Currently, these lines define only a partial list of handsontable events. This list does not include afterColumnSort which would be what you need. Here is a quick hack to partially answer your question.

library(rhandsontable)
library(shiny)
library(htmlwidgets)

runApp(shinyApp(
  ui = fluidPage(
    rHandsontableOutput("hot"),
    tags$script(
'
setTimeout(
  function() {
    HTMLWidgets.find("#hot").hot.addHook(
      "afterColumnSort",
      function(){
        console.log("sort",this);
        Shiny.onInputChange(
          "hot_sort",
          {
            data: this.getData()
          }
        )
      }
    )
  },
  1000
)
' 

    )
  ),
  server = function(input, output, session) {
    observeEvent(
      input$hot_sort
      ,{
        print(input$hot_sort$data)
      }
    )

    output$hot <- renderRHandsontable({
      if (!is.null(input$hot)) {
        DF <- hot_to_r(input$hot)
      } else {
        DF <- mtcars
      }
      rhandsontable(DF) %>%
        hot_table(highlightCol = TRUE, highlightRow = TRUE) %>%
        hot_cols(columnSorting = TRUE)
    })
  }
))
like image 53
timelyportfolio Avatar answered Nov 15 '22 05:11

timelyportfolio