【问题标题】:Negating logical values from input in R shiny从 R 中的输入中取反逻辑值
【发布时间】:2021-06-24 14:22:39
【问题描述】:

当我在 Shiny 应用程序的 server() 函数中否定 input 的逻辑值时,我很困惑为什么会得到 Error: invalid argument type。在下面的最小示例中,input[['log_scale']] 显然是一个逻辑(布尔)变量,但语句 if(!input[['log_scale']]) 失败。删除否定运算符! 使代码工作,但对于我的实际应用程序,我希望能够包含条件语句,否定从input 参数传递给server() 的一些逻辑值。

编辑:我尝试按照 YBS 的建议使用 ==FALSE 而不是 !。如果我的if 语句中有多个条件并用& 分隔,这仍然会导致问题。请参阅下面的代表。

library(shiny)

ui <- fluidPage(
  
  # Application title
  titlePanel('Test'),
  
  # Sidebar with options
  sidebarLayout(
    sidebarPanel(
      radioButtons("foo",
                   "foo",
                   c('Yes' = TRUE,
                     'No' = FALSE)),

      radioButtons('log_scale',
                   'Log-transform y-axis?',
                   c('Yes' = TRUE,
                     'No' = FALSE)),
      
    ),
    
    
    mainPanel(
      plotOutput('plot')
    )
  )
)

server <- function(input, output) {
  output$plot <- renderPlot({
    dat <- data.frame(x = 1:5, y = 10^(1:5))
    if (input[['foo']] & input[['log_scale']] == FALSE) title = "log scale plot" else title = "not log scale plot"
    if (input[['log_scale']] == FALSE) z = '' else z = 'y'

    plot(dat$x, dat$y, log = z, main = title)
  })
}

shinyApp(ui, server)

【问题讨论】:

  • 或许你可以使用if (input[['log_scale']]==FALSE) z = '' else z = 'y'
  • Argh,在 reprex 中有效,但在我的实际代码中无效。我得到Error: operations are possible only for numeric, logical or complex types。即使我确信我的输入值是合乎逻辑的。我错过了什么吗?我可能需要找到更好的代表。
  • @YBS 我发现当以&amp; 分隔的多个条件被传递给if 语句时,即使我使用==FALSE,也会出现问题行为。我已经编辑了示例以反映这一点。
  • OK 我认为解决方案是使用input[['foo']] == TRUE &amp; input[['log_scale']] == FALSE,换句话说,将所有条件都写出来。

标签: r shiny


【解决方案1】:

radioButtons 产生字符类型值,因此进行类型转换可以解决问题。

library(shiny)

ui <- fluidPage(
    
    # Application title
    titlePanel('Test'),
    
    # Sidebar with options
    sidebarLayout(
        sidebarPanel(
            radioButtons("foo",
                         "foo",
                         c(TRUE = 'yes',
                          FALSE = 'no')),
            radioButtons('log_scale',
                         'Log-transform y-axis?',
                         c('Yes' = TRUE,
                           'No' = FALSE)),
            
        ),
        mainPanel(
            plotOutput('plot')
        )
    )
)

server <- function(input, output) {
    output$plot <- renderPlot({
        
        dat <- data.frame(x = 1:5, y = 10^(1:5))
        if (as.logical(input[['foo']]) & !as.logical(input[['log_scale']])) title = "log scale plot" else title = "not log scale plot"
        if (!as.logical(input[['log_scale']])) z = '' else z = 'y'
        
        plot(dat$x, dat$y, log = z, main = title)
    })
}

shinyApp(ui, server)

【讨论】:

  • 好吧,这很有意义。我想一个更好的解决方案是对是/否选项使用复选框来获得逻辑值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-25
  • 2011-03-27
相关资源
最近更新 更多