mike
mike

Reputation: 951

Reactivity and rhandsontable

I have slightly modified what I saw here: Get selected rows of Rhandsontable as a little tester for what I will use rhandsontable for. I want to be able to let users change values of the data frame from within r using the rhandsontable package. So here I want df[1,1] to update each time I change that value. I am just a bit confused when it comes to wrapping a reactive function around render functions especially the renderRHandsontable function. I have used reactive functions with plotting but this is a bit different.

library(shiny)
library(rhandsontable)

ui=fluidPage(
  rHandsontableOutput('table'),
  verbatimTextOutput('selected'),
    verbatimTextOutput("tr")
)
server=function(input,output,session)({

a<-c(1,2)
b<-c(3,4)
c<-rbind(df1,df2)
df1<-data.frame(df3)

#need reactive function around the following

  output$table=renderRHandsontable(
    rhandsontable(df1,selectCallback = TRUE,readOnly = FALSE)
  )
  output$selected=renderPrint({
    cat('Selected Row:',input$table_select$select$r)
    cat('\nSelected Column:',input$table_select$select$c)
    cat('\nSelected Cell Value:',input$table_select$data[[input$table_select$select$r]][[input$table_select$select$c]])
    df1[input$table_select$select$r,input$table_select$select$c]<-input$table_select$data[[input$table_select$select$r]][[input$table_select$select$c]]
  })
 #need reactive function around the following
  output$tr <- renderText({
df1[1,1]
})

})
# end server
shinyApp(ui = ui, server = server)

Upvotes: 2

Views: 4822

Answers (1)

onlyphantom
onlyphantom

Reputation: 9573

Your code here is not reproducible. In the beginning of your server function, you used rbind() on df1 and df2when neither of these objects exist yet. R will throw an error (and it should!)

Because of that I will have to assume that your data frame is in fact the following:

  a<-c(1,2)
  b<-c(3,4)
  c<-rbind(a,b)
  df1<-data.frame(c)

To bind the reactivity output from Rhandsontable to your textOutput, you can use the observe() function from Shiny or even better, the handy hot_to_r function from rhandsontable itself. This function converts the handsontable data to R object.

Without changing your ui function, this will be your server function:

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

    a<-c(1,2)
    b<-c(3,4)
    c<-rbind(a,b)
    df1<-data.frame(c)

output$table<-renderRHandsontable(
      rhandsontable(df1)
)

#use hot_to_r to glue 'transform' the rhandsontable input into an R object
output$tr <- renderText({
      hot_to_r(input$table)[1,1]
})

})

Then proceed to call your Shiny app as usual: shinyApp(ui = ui, server = server) and your output$tr now reacts to any edits on your table.

Upvotes: 2

Related Questions