问题
I am trying to simply update a column of a dataframe once a user presses a button in Shiny. I am a little confused as to how the currently showing dataframe is passed to the server side function.
Once the button is pressed the column cyl should be increased by 10. If the button is pressed again the column should take the recalculated values and multiply by a further 10 etc.
So far I have done this but nothing seems to happen when the button is pressed.
---
title: "My dataframe refresh"
output: html_document
runtime: shiny
---
```{r, echo=FALSE}
library(EndoMineR)
shinyApp(
ui <- fluidPage(
DT::dataTableOutput("mytable"),
actionButton("do", "Click Me")
),
server = function(input, output,session) {
#Load the mtcars table into a dataTable
output$mytable = DT::renderDataTable({
mtcars
})
#A test action button
observeEvent(input$do, {
renderDataTable(mtcars$cyl*10)
})
},
options = list(height = 800)
)
```
回答1:
Try this:
library(shiny)
library(DT)
RV <- reactiveValues(data = mtcars)
app <- shinyApp(
ui <- fluidPage(
DT::dataTableOutput("mytable"),
actionButton("do", "Click Me")
),
server = function(input, output,session) {
#Load the mtcars table into a dataTable
output$mytable = DT::renderDataTable({
RV$data
})
#A test action button
observeEvent(input$do, {
RV$data$cyl <- RV$data$cyl * 10
})
}
)
runApp(app)
I always store my data frames, especially if they should be reactive in a reactiveValues list. After that you just render the data, and in the observe step overwrite the original data frame. You have to explicitly overwrite data to store results, mtcars$cyl * 10 won't affect the mtcars data frame.
来源:https://stackoverflow.com/questions/50251813/how-to-update-datatable-in-shiny-with-button