【问题标题】:Using an if else statment in a reactive function for a Shiny app在 Shiny 应用程序的反应函数中使用 if else 语句
【发布时间】:2021-12-06 22:29:50
【问题描述】:

我正在尝试在反应函数中使用 if else 语句来输出基于用户输入的数据集,该用户输入是下拉菜单中的选择。但似乎无论我选择什么,我总是得到“其他”输出。有人可以帮忙吗?提前致谢!

 extract_name <- function(v1) {
        deparse(substitute(v1))
    }

 plotly_data <- reactive({
        
        if (grepl("fdr", extract_name(input$fsChoice)) == TRUE) {
        
            edited_data <- fs_data %>%
                dplyr::select(region, hemi, metric, input$fsChoice) %>%
                dplyr::filter(metric == input$metric) %>%
                dplyr::filter(hemi == input$hemi) %>%
                dplyr::filter(noninput$fsChoice > 1.30103)
            
        }
        
        else {
            
            edited_data <- fs_data %>%
                dplyr::select(region, hemi, metric, input$fsChoice) %>%
                dplyr::filter(metric == input$metric) %>%
                dplyr::filter(hemi == input$hemi)
        }
        
        return(edited_data)
        
        }
    )

【问题讨论】:

  • == TRUE in if 是多余的。 extract_name 函数是什么?您是否在闪亮的应用程序之外对其进行了测试以确保其行为符合预期?
  • 嗨罗纳克!我已编辑问题以包含该功能。我已经在外面测试过,它确实有效!

标签: r shiny reactive-programming reactive


【解决方案1】:

deparse(substitute(...)) 在您将变量传递给它时表现不同。

extract_name <- function(v1) {
  deparse(substitute(v1))
}

var <- "abc"
extract_name("abc")
#[1] "\"abc\""
extract_name(var)
#[1] "var"

在这种情况下,我认为您不需要extract_name 函数。尝试直接使用input$fsChoice

plotly_data <- reactive({
        if (grepl("fdr",input$fsChoice)) {
        
            edited_data <- fs_data %>%
                dplyr::select(region, hemi, metric, input$fsChoice) %>%
                dplyr::filter(metric == input$metric) %>%
                dplyr::filter(hemi == input$hemi) %>%
                dplyr::filter(noninput$fsChoice > 1.30103)
            
        }
        else {
            edited_data <- fs_data %>%
                dplyr::select(region, hemi, metric, input$fsChoice) %>%
                dplyr::filter(metric == input$metric) %>%
                dplyr::filter(hemi == input$hemi)
        }
        return(edited_data)
        }
    )

【讨论】:

  • 不幸的是,这不起作用。我收到错误:警告:错误:filter() 输入 ..1 有问题。 ℹ 输入..1noninput$fsChoice &gt; 1.30103。未找到 x 对象“非输入”135:
  • 好吧,抱歉这个错误似乎与我对代码的更改无关。 object 'noninput' not found 至少确认我的代码有效,并且在 dplyr::filter(noninput$fsChoice &gt; 1.30103) 这一行中失败了。我无法进一步测试它,因为您没有提供可重现的示例,而且我不知道 noninput 是什么。
猜你喜欢
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多