I am trying to dynamically change a formula in a shiny application based on the input.
Currently I can build the formula using the default starting settings, but whenever I change the inputs, the formula goes back to the raw mathjax input, rather than displaying the formula.
Is it possible to keep the formula dynamic but keep it being rendered as a formula?
See the code below:
library(shiny)
ui <- fluidPage(
fluidPage(
titlePanel("T-test example"),
fluidRow(
column(3, wellPanel(
sliderInput("mean1", "Group 1 mean:",
min = 10, max = 1000, value = 200,
step = 10),
sliderInput("sd1", "Group 1 variation:",
min = 10, max = 100, value = 50,
step = 10),
sliderInput("mean2", "Group 2 mean:",
min = 10, max = 1000, value = 200,
step = 10),
sliderInput("sd2", "Group 2 variation:",
min = 10, max = 100, value = 50,
step = 10)
)),
column(6,
plotOutput("plot1", width = 400, height = 300),
br(),
p(
withMathJax(
"$$t = \\frac{\\bar{x}_1 - \\bar{x}_2}{\\sqrt{\\frac{s_1^2}{N_1}+\\frac{s_2^2}{N_2}}}$$"
)),
textOutput("formula")
)
)
)
)
server <- function(input, output, session) {
output$plot1 <- renderPlot({
x = rnorm(500, mean = input$mean1,
sd = 20)
y = rnorm(500, mean = input$mean2,
sd = 20)
boxplot(x,y)
})
output$formula <- reactive({
str = sprintf("$$t = \\frac{%d - %d}{\\sqrt{\\frac{%d}{N_1}+\\frac{%d}{N_2}}}$$",
input$mean1,
input$mean2,
input$sd1,
input$sd2
)
str
})
observeEvent(input$change,
{
output$formula <- renderText({
formula()
})
})
}
shinyApp(ui, server)
One possible option is to not use renderText
, but renderUI
. Also, the way you use observeEvent
and reactive
seems a bit off. A reactive
does not need an observeEvent
to get updated, since it is invalidated if one of its inputs changes automatically. If you want to have more influence over when something changes, maybe use a reactiveVal instead of a reactive
.
Anyway, here is a working example, I hope this helps!
library(shiny)
ui <- fluidPage(
fluidPage(
titlePanel("T-test example"),
fluidRow(
column(3, wellPanel(
sliderInput("mean1", "Group 1 mean:",
min = 10, max = 1000, value = 200,
step = 10),
sliderInput("sd1", "Group 1 variation:",
min = 10, max = 100, value = 50,
step = 10),
sliderInput("mean2", "Group 2 mean:",
min = 10, max = 1000, value = 200,
step = 10),
sliderInput("sd2", "Group 2 variation:",
min = 10, max = 100, value = 50,
step = 10)
)),
column(6,
plotOutput("plot1", width = 400, height = 300),
br(),
p(
withMathJax(
"$$t = \\frac{\\bar{x}_1 - \\bar{x}_2}{\\sqrt{\\frac{s_1^2}{N_1}+\\frac{s_2^2}{N_2}}}$$"
)),
uiOutput("formula")
)
)
)
)
server <- function(input, output, session) {
output$plot1 <- renderPlot({
x = rnorm(500, mean = input$mean1,
sd = 20)
y = rnorm(500, mean = input$mean2,
sd = 20)
boxplot(x,y)
})
output$formula <- renderUI({
p(
withMathJax(sprintf("$$t = \\frac{%d - %d}{\\sqrt{\\frac{%d}{N_1}+\\frac{%d}{N_2}}}$$",
input$mean1,
input$mean2,
input$sd1,
input$sd2
)))
})
}
shinyApp(ui, server)