你可以使用一个reactive
表达式num_C
library(shiny)
# Define UI
ui <- fluidPage(
numericInput(inputId = "A", "Number A", value = 2),
numericInput(inputId = "B", "Number B", value = 3),
numericInput(inputId = "C", "Number C [A/B]", value = 1)
)
# Server logic
server <- function(input, output, session){
num_C <- reactive({
req(input$A, input$B)
input$A / input$B
})
observe(
updateNumericInput(
inputId = "C",
session = session,
value = format(num_C(), digits = 2))
)
}
# Complete app with UI and server components
shinyApp(ui, server)
num_C()
然后将返回“未舍入”的值,而我们format(num_C(), digits = 2)
在updateNumericInput
.
部分更新
对于它的价值,这是一个不完整的更新
library(shiny)
# Define UI
ui <- fluidPage(
numericInput(inputId = "A", "Number A", value = 2),
numericInput(inputId = "B", "Number B", value = 3),
numericInput(inputId = "C", "Number C [A/B]", value = 1),
textOutput("value"),
textOutput("rounded_value")
)
# Server logic
server <- function(input, output, session){
num_C <- reactiveValues(
value = NULL,
rounded_value = NULL
)
observeEvent(input$A | input$B, {
num_C$value <- input$A / input$B
num_C$rounded_value <- round(num_C$value, 1)
})
observeEvent(input$C, {
num_C$value <- input$C
num_C$rounded_value <- input$C
})
output$value <- renderText(
sprintf("Number C = %f", num_C$value)
)
output$rounded_value <- renderText(
sprintf("Number C (rounded) = %f", num_C$rounded_value)
)
}
# Complete app with UI and server components
shinyApp(ui, server)
这个想法是用来reactiveValues
跟踪数字 C 的完整精度和舍入值。这适用于
- 通过更改数字 A、B
numericInput
将正确计算(并显示)textOutput
s 中 C 的完整精度和舍入数字。
- 更改数字 C
numericInput
也将正确显示 s 中的完整精度数字(等于四舍五入)textOutput
。
但是updateNumericInput
,当数字 A 和 B 发生变化时,我无法成功地使用四舍五入的数字更新 C 的值。
未完待续...