【问题标题】:If/else statement does not evaluate properly shiny/Rif/else 语句未正确评估闪亮/R
【发布时间】:2016-05-11 12:08:58
【问题描述】:

使用闪亮的 R.

在我的ui.R 中,我有一个看起来像这样的元素

radioButtons("startEnd",
    label = "Choose",
    choices = list("start" = 1,
    "end" = 2),
    selected = NA,
    inline = TRUE
) 

在我的server.R 我有这个

observeEvent(input$startEnd, {
    print(input$startEnd)
    if (!is.null(as.integer(input$startEnd)) == 1) {
            print("Gone in if")
    } else if (!is.null(as.integer(input$startEnd)) == 2) {
            print("Gone in else if")
    } else {
            print("Gone in nothing")
    }       
}) 

但是,它的计算结果始终为 print("Gone in if")但是我的第一个 print(input$startZiel) 会根据我在应用中点击的内容打印出正确的数字。

【问题讨论】:

  • is.null() == 1 没有多大意义。只需使用is.null()if 需要一个布尔值,is.null() 输出一个布尔值。我不知道is.null()==2 想要完成什么......

标签: r if-statement boolean shiny


【解决方案1】:

您当前正在做的是将input$startEnd 转换为整数,通过否定其空值将该整数转换为布尔值,然后将该布尔值与整数进行比较。因为您的数字不为空,布尔值的计算结果为 TRUE,即等于 1,因此第一个条件始终成立。我想你想要的其实是这样的,

observeEvent(input$startEnd, {
print(input$startEnd)
asInt = as.integer(input$startEnd)
if(!is.null(asInt)) {
    if (asInt == 1) {
        print("Gone in if")
    } else if (asInt == 2) {
        print("Gone in else if")
    } else {
        print("Gone in nothing")
    }  
}     

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    相关资源
    最近更新 更多