如何格式化 Shiny 更新的 numericInput 的输入但不更改实际值?

www*_*www 5 javascript format r shiny numeric-input

在以下示例中,numberInput“编号 C”的计算和更新为“编号 A”除以“编号 B”。当结果是无限小数时,这会导致一个数字很多的数字为“数字 C”。我想将无限小数四舍五入到数字的第二个或第三个,使“数字 C”的外观更易于阅读。但是,与此同时,我不想应用该round函数,num_C因为在现实世界中,我想将“数字 C”应用于其他计算,并且我想按原样使用该数字。换句话说,我想找到一种方法来格式化数字的外观而不是实际值,例如格式化 Excel 电子表格中的单元格以仅显示有限的数字但不更改实际值。这可以在 Shiny 中做到吗?

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){

  observe({
    req(input$A, input$B)
    num_C <- input$A/input$B
    updateNumericInput(
      inputId = "C",
      session = session,
      value = num_C
    )
  })
}

# Complete app with UI and server components
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

Mau*_*ers 5

你可以使用一个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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

这个想法是用来reactiveValues跟踪数字 C 的完整精度和四舍五入的值。这适用于

  1. 更改数字 A、B 通过numericInput将正确计算(并显示)textOutputs 中C 的完整精度和四舍五入数字。
  2. 通过更改数字 CnumericInput也将正确显示textOutputs 中的全精度数字(等于舍入)。

但是updateNumericInput当数字 A 和 B 发生变化时,我无法成功地使用四舍五入的数字更新 C 的值。

未完待续...