Reputation: 21
If I have a rather time consuming analysis, let's say fitting a model to some data set. I want to display all the output of the model fitting, say there will be renderPlot(), renderTable(), renderText(), etc. How do I render all of them with the model running only once? My current code looks like the following:
shinyServer(function(input, output,session) {
output$twang_diagplot <- renderPlot({
if(is.null(data())|input$twang_x=='.'|input$twang_y=='.') return(NULL)
else{
formula <- paste(input$twang_y, "~",paste(input$twang_x,collapse='+'))
ps_fit <- ps(as.formula(formula),data=workdata(),verbose=FALSE)
plot(ps_fit)
}
})
output$twang_summary <- renderPrint({
if(is.null(data())|input$twang_x=='.'|input$twang_y=='.') return(NULL)
else{
formula <- paste(input$twang_y, "~",paste(input$twang_x,collapse='+'))
ps_fit <- ps(as.formula(formula),data=workdata(),verbose=FALSE)
ps_balance <- bal.table(ps_fit)
print(ps_balance)
}
})
})
In the above example, I had to call the ps() function twice to generate plot and summary separately. This is very inefficient. I know there should be a function such as reactive() or observe() that I could use to wrap the two render functions together after calling the ps() function but I'm not sure how to use it. Would appreciate your help! regards
shinyServer(function(input, output,session) {
getPsFit <- reactive({
formula <- paste(input$twang_y, "~",paste(input$twang_x,collapse='+'))
ps_fit <- ps(as.formula(formula),data=workdata(),verbose=FALSE)
ps_fit
})
output$twang_diagplot <- renderPlot({
if(is.null(data())|input$twang_x=='.'|input$twang_y=='.') return(NULL)
else{
ps_fit <- getPsFit()
plot(ps_fit)
}
})
output$twang_summary <- renderPrint({
if(is.null(data())|input$twang_x=='.'|input$twang_y=='.') return(NULL)
else{
ps_fit <- getPsFit()
ps_balance <- bal.table(ps_fit)
print(ps_balance)
}
})
})
Upvotes: 2
Views: 3129
Reputation: 26373
It looks like the two calls to ps()
are using different arguments, so I'm not sure you can use a reactive in this case that will only be called once because ps
would have to be called twice, I don't see a way around that...
PS. your code could benefit from some more spacing to make it a lot more readable :)
edit after your comment:
Have you read the Shiny tutorial, specifically the section of reactive expressions?
Something like this should work
getPsFit <- reactive({
formula <- paste(input$twang_y, "~",paste(input$twang_x,collapse='+'))
ps_fit <- ps(as.formula(formula),data=workdata(),verbose=FALSE)
ps_fit
})
now just replace your two lines of code in both else statements with ps_fit <- getPsFit()
Upvotes: 4