【问题标题】:sliderTextInput displays incorrect values?sliderTextInput 显示不正确的值?
【发布时间】:2020-11-27 09:30:38
【问题描述】:

我正在尝试根据来自 sliderTextInput 的值输出某个数字,但由于某种原因,随着滑块的变化,它似乎没有显示正确的值。我对 sliderTextInput 的选择列表是 ("0", "1", "2", ">2"),对于这些值中的每一个,它应该呈现一个文本值 (0, 25, 50, 75 ),但通常从不显示 0 的值,并且这些值似乎移动了一个值。这是该问题的可重现示例:

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  sliderTextInput("slider1", label = "What is your Score?", 
                  choices = c("0","1", "2", ">2"), selected = "0"),

    textOutput("score")
)

server <- function(input, output, session) {
  output$score <- renderText(switch(input$slider1,
                                  "0"  = 0,
                                  "1"  = 25,
                                  "2"  = 50,
                                  ">2" = 75))
}
shinyApp(ui, server)

我认为这可能是因为它无法解释字符串和数字的混合(例如 ">2" 与 "2"),或者值 0 的解释可能不同,但更改这些没有效果。我能够让它工作的唯一方法是,如果我将每个输入值更改为一个清晰的字符串(例如“零”、“一”、“二”、“二”)。但是,用引号括起来的数字是否会强制评估为字符,而不是数字?还是我完全错过了这个错误?

【问题讨论】:

    标签: r shiny shinywidgets


    【解决方案1】:

    这可能与 switch 的工作方式有关,例如,来自其帮助页面,

    如果匹配,则评估该元素,除非它缺失,在这种情况下评估下一个非缺失元素,例如 switch("cc", a = 1, cc =, cd =, d = 2) 计算结果为 2。

    ...尤其是与sliderTextInput 结合使用——我注意到,如果您简单地定义output$score &lt;- renderText(input$slider1),当滑块设置为0 时它不会呈现任何内容。所以我不太确定发生了什么。

    获得所需输出的一种方法(虽然不如switch 漂亮)是使用dplyr::case_when,例如,

    server <- function(input, output, session) {
        output$score <- renderText(
            dplyr::case_when(
                input$slider1 == "0" ~ 0,
                input$slider1 == "1" ~ 25,
                input$slider1 == "2" ~ 50,
                input$slider1 == ">2" ~ 75))
    }
    

    【讨论】:

    • 是的,正如@Waldi 类似指出的那样,这似乎是开关的问题。我认为可能有一些启发式方法会自动将像“0”这样的文本转换为其整数形式,并且因为 switch 需要完全匹配,所以它会以某种方式搞砸。感谢您提供 dplyr 替代方案,我会记住的!
    【解决方案2】:

    switch 要求完全匹配,但如果你输出:

    output$score <- renderText(class(input$slider1))
    

    您会看到 3 个第一个选项返回 integer,而最后一个返回 character

    input$slider1 投射到角色作品中:

    library(shiny)
    library(shinyWidgets)
    
    ui <- fluidPage(
      sliderTextInput("slider1", label = "What is your Score?", 
                      choices = c("0","1", "2", ">2"), selected = "0"),
      
      textOutput("score")
    )
    
    server <- function(input, output, session) {
      output$score <- renderText(switch(as.character(input$slider1),
                                        "0"  = 0,
                                        "1"  = 25,
                                        "2"  = 50,
                                        ">2" = 75))
    }
    shinyApp(ui, server)
     
    

    【讨论】:

    • 啊,我明白了!我实际上曾尝试将 sliderTextInput 选项转换为字符,但没有意识到我必须改为转换输入。而且我什至没有意识到这是开关而不是滑块文本输入的问题。成功了,谢谢!
    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2019-02-22
    • 2017-07-18
    相关资源
    最近更新 更多