В следующем примере объект R fit
создается в shiny::renderPrint
, но не в renderPlot
. Таким образом, заговор сделан для print()
, но не plot()
.
В реальной фазе fit
- это подобранный объект модели, сгенерированный rstan:sampling()
, и это занимает очень много времени, поэтому я не буду выполнять его дважды как в renderPrint
, так и renderPlot
. Есть ли идея? Я очень начинающий Shiny.
library(shiny)
ui <- fluidPage(
mainPanel(
shiny::sliderInput("aaa",
"aaa:",
min = 1, max = 11111, value = 5),
shiny::plotOutput("plot"),
shiny::verbatimTextOutput("print") )
)
server <- function(input, output) {
output$print <- shiny::renderPrint({
fit <- input$aaa*100 # First creation of object,
# and we use it in the renderPlot.
# So, we have to create it twice even if it is exactly same??
# If possible, I won't create it
# In the renderPlot, twice.
print(fit)
})
output$plot <- shiny::renderPlot({
# The fit is again created
# If time to create fit is very long, then total time is very heavy.
# If possible, I do not want to make fit again.
fit <- input$aaa*100 #<- Redundant code or I want to remove it.
plot(1:fit)
})
}
shinyApp(ui = ui, server = server)
Редактировать
Чтобы избежать дублирования кода создания объекта, я использую следующее, тогда все идет хорошо. Спасибо, @ bretauv.
library(shiny)
ui <- fluidPage(
mainPanel(
shiny::sliderInput("aaa",
"aaa:",
min = 1, max = 11111, value = 5),
shiny::plotOutput("plot"),
shiny::verbatimTextOutput("print") )
)
server <- function(input, output) {
########## Avoid duplicate process ###################
test <- reactive({input$aaa*100})
#####################################################################
output$print <- shiny::renderPrint({
# fit <- input$aaa*100 # No longer required
print(test())
})
output$plot <- shiny::renderPlot({
# fit <- input$aaa*100 # No longer required
plot(1:test())
})
}
shinyApp(ui = ui, server = server)