【问题标题】:If statement returning last conditionif 语句返回最后一个条件
【发布时间】:2022-01-03 19:09:24
【问题描述】:

我一直在做一些与 R Shiny 相关的工作。我对 R 很陌生,这可能是一个简单的语法错误。

下面的代码是我的 server.r 和 renderText(mx()) 似乎只返回最后一个按时间顺序排列的 if 语句的输出。 (当我交换它们时,它会相应地改变)。 input$numbers 是我将其更改为列表的文本输入,而 input$mean_type 对应于具有以下选项的单选按钮

radioButtons('mean_type', 'Which operation?',
c('Arithmetic Mean' = 'A', 'Geometric Mean' = 'G', 'Variance' = 'V'))

任何帮助将不胜感激,谢谢!

mx <- reactive({
            x <- as.numeric(unlist(strsplit(input$numbers,",")))
            if (input$mean_type == 'A') {
                mean(x)
            }
            
            if (input$mean_type == 'V') {
                sd(x)
            }
            
            if (input$mean_type == 'G') {
                geometric.mean(x)
            }
        })
output$mean <- renderText(mx())

【问题讨论】:

  • 如果传递给reactive()的表达式主体中没有return,则返回最后一个计算表达式的值,即geometric.mean(x),如果最后一个条件计算为TRUENULL 否则。解决方案可能是在每个 if 块中添加 returns,或者使用 if-else 路由

标签: r shiny reactive


【解决方案1】:

您需要在后续语句中使用else if 而不是if - 否则,您后续的if 语句会附加一个隐含的else NULL 分支;也就是说,

if (a) A
if (b) B

其实是一样的

if (a) A else NULL
if (b) B else NULL

R 中一系列语句的值是该序列中最后一个表达式的值。

所以你的代码应该如下所示:

mx <- reactive({
    x <- as.numeric(unlist(strsplit(input$numbers,",")))
    if (input$mean_type == 'A') {
        mean(x)
    } else if (input$mean_type == 'V') {
        sd(x)
    } else if (input$mean_type == 'G') {
        geometric.mean(x)
    }
})

或者,您可以使用提前退出;也就是用return(mean(x))代替mean(x)等。不过我更喜欢上面的方案。

【讨论】:

  • 非常感谢,完美运行!从这个意义上说,语法不像 python。
  • @Ben 是的,Python 在这方面与 R 有根本的不同,因为在 R 中每个表达式都有一个值。在 Python 中情况并非如此,如果要返回值,您总是需要显式使用 return
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 2018-05-07
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
相关资源
最近更新 更多