我目前正在做一個 R Shiny 專案,下面是我在實際專案中嘗試完成的事情的一個小例子。基本思想是通過 eventReactive 函式中的條件陳述句處理從用戶輸入生成的反應資料表。在下面的示例中,我想使用條件“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())
})
}
uj5u.com熱心網友回復:
您不能使用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)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471125.html
