【发布时间】:2021-07-05 12:26:36
【问题描述】:
我正在构建我的第一个 Shiny 应用程序来替换 Excel 报告。一项必要的功能是能够编辑表中的数据并查看汇总值随用户输入的值更新的选项。
我一直在搞清楚如何捕获该新值并使用该新值刷新汇总表。
如果还有类似的问题,请分享。
我尝试过使用 Observe、ObserveEvent 和 Reactive。我没有完全掌握这些概念,但是,当我按预期使用它们时,它们就按我的预期工作了。
我已尝试使用一些可用的 R 数据集来重现该问题。请参阅下面的代码。
包含基于用户选择的初始数据的 tableOutput 是可编辑的。因此,当在该列中放置一个新数字时,我希望 summaryOutput 会相应地更新和反映。
非常感谢任何指导或意见!一旦可行,这将是对 Excel 的巨大胜利。
谢谢!
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(DT)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30),
selectInput("data",
"Select Dataset",
choices = c( "iris", "mtcars", "faithful"),
selected = "faithful")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
DT::dataTableOutput("tableOutput"),
DT::dataTableOutput("summaryOutput"),
textOutput("text")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
# https://nbisweden.github.io/RaukR-2019/shiny/lab/shiny_lab.html
getdata <- reactive({ get(input$data, 'package:datasets') })
getsummary <- reactive({summary(getdata()[2])})
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- as.numeric(getdata()[,2])
xname <- colnames(getdata()[2])
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white',
main = paste("Histogram of" , xname),)
#hist(x)
})
output$tableOutput <- DT::renderDataTable({
DT::datatable(getdata(),
editable = TRUE,
options = list(orderClasses = TRUE
)
)
})
output$summaryOutput <- DT::renderDataTable({
DT::datatable(getsummary())
})
proxy = dataTableProxy('tableOutput')
observeEvent(input$x1_cell_edit, {
info = input$x1_cell_edit
str(info)
i = info$row
j = info$col
v = info$value
getdata()[i, j] <<- DT::coerceValue(v, getdata()[i, j])
replaceData(proxy, getdata(), resetPaging = FALSE) # important
})
}
# Run the application
shinyApp(ui = ui, server = server)
【问题讨论】: