Thank you pieterjanvc. I think I should make my problem clear.
You can see my code as follow.
1.The code is OK but I want to improve it.
library("shiny")
ui <- navbarPage("Reprex",
tabPanel("Page1",textOutput("res1")),
tabPanel("Page2",textOutput("res2"))
)
server = function(input,output){
#I use rdata for example. In my real code, it's a sql code which get data from my database.
#The question is that my database is too large and need sql twice.
#I don't want to run these two sql at the beginnig.
#Can I run the second code when I change to Page2?
#Then users who don't want to view Page2 don't need to wait too long for unnecessary data load.
data("iris")
data("mtcars")
output$res1 <- renderText(names(iris))
output$res2 <- renderText(names(mtcars))
}
shinyApp(ui, server)
2.I found the problem is the isolate function. And it's also a improvement problem.
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("select_class","choose class",
choices = c("class1","class2"),
selected = "class1"),
tableOutput("datavar")
),
mainPanel(
uiOutput("select_name"),
actionButton("select_name_active","See final result"),
tableOutput("finaloutput"))
)
)
server <- function(input, output) {
#data example:
data = data.frame(name = c("A","A","B","B","C","C",
"D","D","E","E","F","F"),
score = rnorm(12),
class = rep(c("class1","class2"),each = 6))
#a reactive expression to choose my data.
selectdata = reactive({data[data$class == input$select_class,]})
#Present a index for user.
#I wish they can choose any "x" type,But there are too large data to explore.
#So I set a index for their inference. Like var, I will choose the "x" of max var by default.
#And this index will enter the data fliter part directly and present a result.
datavar <- reactive({
res = aggregate(selectdata()$score,
by = list(selectdata()$name),
var)
colnames(res) = c("name","scoreVar")
res
})
output$datavar <- renderTable({
datavar()
})
output$select_name = renderUI({
selectInput("select_name","choose name",
choices = unique(datavar()$name),
selected = datavar()$name[which.max(datavar()$scoreVar)]
)
})
#In my real code,select_name have many input.I didn't want that changing anyone will triggle a calculation.It may cost time.So I isolate it.
#But selectdata() triggle the first flush so the result is empty at the first.
#And it semms that select_name can't triggle a flush.
#The question is that I want to show a pre-example for user instead of a empty result which must active by actionbutton.
output$finaloutput <- renderTable({
input$select_name_active
isolate(selectdata()[which(selectdata()$name == input$select_name),])
})
}
shinyApp(ui, server)