Shiny App-将输入项保存为变量并在代码中使用

问题描述 投票:0回答:1

我正在使用Shiny App,我需要将数字输入(“ num”)保存为变量,并在ifelse语句中使用它。

例如,我尝试在服务器功能内执行myvalue <- input$num,但它不起作用。

我需要用至少4或5个输入来做到这一点。

有人有想法吗?

shiny shinydashboard shiny-server shinyapps
1个回答
0
投票

选项1:只需在input$num处使用myvalue。这不是问题。

选项2:使用reactive()。注意括号myvalue(),就像调用函数一样调用它。 (此函数)。

library(shiny)

ui <- fluidPage(
  numericInput("num", "Number", 0),
  textOutput("positive"),
  textOutput("odd")
)

server <- function(input, output, session) {

  # Option 1
  output$positive <- renderText({
    if (input$num >= 0) {
      "Positive number."
    } else {
      "Negative number."
    }
  })

  # Option 2
  myvalue <- reactive({
    input$num
  })

  output$odd <- renderText({
    if (myvalue() %% 1 != 0) {
      "Not an integer."
    } else if (myvalue() %% 2 == 0) {
      "Even number."
    } else {
      "Odd number."
    }
  })
}

shinyApp(ui, server)
© www.soinside.com 2019 - 2024. All rights reserved.