代码之家  ›  专栏  ›  技术社区  ›  Navi

if语句在函数中不能解释为逻辑语句

  •  0
  • Navi  · 技术社区  · 2 年前

    我目前正在做一个R闪亮的项目,下面是我在实际项目中努力完成的事情的一个小例子。其基本思想是处理由用户输入通过EventResponsive函数中的条件语句生成的反应数据表。在下面的示例中,我想使用条件“if”语句对用户输入进行加法、乘法或减法。我得到了这样一个错误:“if中的错误:参数不可解释为逻辑”。我知道我没有在这里正确地设置col1进行逻辑比较,似乎找不到解决方案。

    library(shiny)
    library(DT)
    library(tidyverse)
    
    
    input_data <- data.frame(input1 = character(),
                             input2 = double(),
                             stringsAsFactors = FALSE)
    
    ui <- fluidPage(
      
      titlePanel("Title"),
      
      sidebarLayout(
        sidebarPanel(
          selectInput("input1",
                      "Input 1",
                      choices = c("Add", "Multiply", "Subtract")),
          numericInput("input2",
                       "Input 2",
                       value = 100),
          actionButton("add_btn",
                       "Add Input"),
          actionButton("process_btn", 
                       "Process Input"),
          position = "left"
        ),
        
        mainPanel(
          DT::dataTableOutput("input_table"),
          DT::dataTableOutput("output_table")
        )
      )
    )
    
    server <- function(input, output) {
      input_table <- reactiveVal(input_data)
      observeEvent(input$add_btn, {
        t = rbind(input_table(), data.frame(col1 = input$input1, col2 = input$input2))
        input_table(t)
      })
      
      output$input_table <- DT::renderDataTable({
        datatable(input_table())
      })
      
      output_table <- eventReactive(input$process_btn, {
        input_table() %>%
          if(input_table()$col1 == "Add") {
            mutate(col3 = col2 + 50)
          } else if(input_table()$col1 == "Multiply") {
            mutate(col3 = col2 * 50)
          } else 
            mutate(col3 = col2 - 50)
      })
      output$output_table <- DT::renderDataTable({
        datatable(output_table())
      })
    }
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   HubertL    2 年前

    你不能用 if 建造宪法管道 %>% (尤其取决于管道对象的内容)。

    你可以用 ifelse() 相反,或者更好: if_else ()`:

    input_table() %>%
      mutate(col3 = 
        if_else(col1 == "Add",
               col2 + 50,
               if_else(col1 == "Multiply",
                      col2 * 50,
                      col2 - 50)
      )
    

    因为你有几个条件,你也可以使用 case_when() :

    input_table() %>%
      mutate(col3 = 
               case_when(
                 col1 == "Add" ~ col2 + 50,
                 col1 == "Multiply" ~ col2 * 50,
                 TRUE ~ col2 - 50)
             )