#r #shiny
Вопрос:
Я хочу создать блестящее приложение, которое может выполнять последовательные вычисления на основе ввода пользователя. Что-то вроде этого:
a <- input$inputa
b <- a 2
c <- b-3
d <- c*4
e <- d/5
Таким образом , пользователь выберет ввод a
, а блестящее приложение сделает все остальное и покажет значения a
, b
, c
, d
, e
.
Мне удалось это сделать, если приложение всегда делает все расчеты на основе a
. Но если я попытаюсь создать ценность b
и назову ее, она сломается.
Следующий код работает и показывает конечный результат так, как должен, но я уверен, что его можно улучшить, удалив повторения:
# UI
ui <- fluidPage(
# Application title
titlePanel("Doing algebra"),
# Sidebar with numeric input
sidebarLayout(
sidebarPanel(
numericInput("inputa",
"Input a:",
min = 0,
max = 100,
value = 20,
step=1)
),
# Show results of successive calculations
mainPanel(
verbatimTextOutput("output1"),
h4(" 2"),
verbatimTextOutput("output2"),
h4("-3"),
verbatimTextOutput("output3"),
h4("*4"),
verbatimTextOutput("output4"),
h4("/5"),
verbatimTextOutput("output5")
)
)
)
# server
server <- function(input, output) {
output$output1 <- renderText({ input$inputa })
output$output2 <- renderText({ input$inputa 2 })
output$output3 <- renderText({ ( input$inputa 2)-3 })
output$output4 <- renderText({ (( input$inputa 2)-3)*4 })
output$output5 <- renderText({ ((( input$inputa 2)-3)*4)/5 })
}
shinyApp(ui, server)
Последний кусочек, (((input$inputa 2)-3)*4)/5
, выглядит ужасно и является ужасным. Могу ли я создать блестящее приложение, которое создает значение в одном уравнении и использует это значение в следующем уравнении?
Спасибо!
Ответ №1:
Вы можете хранить данные в reactive
выражении.
ui <- fluidPage(
# Application title
titlePanel("Doing algebra"),
# Sidebar with numeric input
sidebarLayout(
sidebarPanel(
numericInput("inputa",
"Input a:",
min = 0,
max = 100,
value = 20,
step=1)
),
# Show results of successive calculations
mainPanel(
verbatimTextOutput("output1"),
h4(" 2"),
verbatimTextOutput("output2"),
h4("-3"),
verbatimTextOutput("output3"),
h4("*4"),
verbatimTextOutput("output4"),
h4("/5"),
verbatimTextOutput("output5")
)
)
)
# server
server <- function(input, output) {
rv <- reactive({
tibble::tibble(a = input$inputa, b = a 2, c = b-3, d = c*4, e = d/5)
})
output$output1 <- renderText({rv()$a})
output$output2 <- renderText({rv()$b})
output$output3 <- renderText({rv()$c})
output$output4 <- renderText({rv()$d})
output$output5 <- renderText({rv()$e})
}
shinyApp(ui, server)