Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save edits made using rhandsontable r package

My R program works as expected. It shows a table containing my dataFrame, and lets me edit the values.

How do I capture those values and save them to my dataframe, or a copy of my dataframe?

require(shiny)
library(rhandsontable)

    DF = data.frame(val = 1:10, bool = TRUE, big = LETTERS[1:10],
                    small = letters[1:10],
                    dt = seq(from = Sys.Date(), by = "days", length.out = 10),
                    stringsAsFactors = F)

    rhandsontable(DF, rowHeaders = NULL)

EDIT: The above code produces a table with rows and columns. I can edit any of the rows and columns. But when I look at my dataFrame, those edits do not appear. What I am trying to figure out is what do I need to change so I can capture the new values that were edited.

like image 676
PaeneInsula Avatar asked Mar 07 '16 00:03

PaeneInsula


1 Answers

I know this thread's been dead for years, but it's the first StackOverflow result on this problem.

With the help of this post - https://cxbonilla.github.io/2017-03-04-rhot-csv-edit/, I've come up with this:

library(shiny)
library(rhandsontable)

values <- list() 

setHot <- function(x) 
  values[["hot"]] <<- x 

DF <- data.frame(val = 1:10, bool = TRUE, big = LETTERS[1:10],
                small = letters[1:10],
                dt = seq(from = Sys.Date(), by = "days", length.out = 10),
                stringsAsFactors = FALSE)


ui <- fluidPage(
  rHandsontableOutput("hot"),
  br(),
  actionButton("saveBtn", "Save changes")
)

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

  observe({
    input$saveBtn # update dataframe file each time the button is pressed
    if (!is.null(values[["hot"]])) { # if there's a table input
      DF <<- values$hot
    }
  })

  observe({
    if (!is.null(input$hot)){
      DF <- (hot_to_r(input$hot))
      setHot(DF)
    } 
  })


  output$hot <- renderRHandsontable({ 
    rhandsontable(DF) %>% # actual rhandsontable object
      hot_table(highlightCol = TRUE, highlightRow = TRUE, readOnly = TRUE) %>%
      hot_col("big", readOnly = FALSE) %>%
      hot_col("small", readOnly = FALSE)
  })

}

shinyApp(ui = ui, server = server)

However, I don't like my solution on the part of DF <<- values$hot as I previously had problems with saving changes to the global environment. I've couldn't figure it out any other way, though.

like image 147
Vesnič Avatar answered Sep 29 '22 13:09

Vesnič