R Shiny Link多路输入至控制1输出

bqjvbblv  于 2023-01-15  发布在  其他
关注(0)|答案(2)|浏览(113)

我有一个闪亮的应用程序,我在那里显示相同的输出多次。我有两个输入,他们都需要控制相同的输出。在我下面的例子中,输出是对方的副本,它必须保持这种方式。目前只有第一个输入做任何事情。我需要他们控制相同的输出,并对对方的变化作出React。

ui <- function(request) {
    fluidPage(
        textInput("txt1", "Enter text1"),
        textInput("txt1", "Enter text2"),
        checkboxInput("caps", "Capitalize"),
        verbatimTextOutput("out1"),
        verbatimTextOutput("out2"),
        
    )
}
server <- function(input, output, session) {
    output$out2<- output$out1 <- renderText({
        if (input$caps)
            toupper(input$txt1)
        else
            input$txt1
        
    })
}

shinyApp(ui, server, enableBookmarking = "url")
sd2nnvve

sd2nnvve1#

你需要给予你的输入唯一的ID,但是在你的代码中两个ID都是txt1。如果你改变这个,你可以使用正常的React性:

library(shiny)

ui <- function(request) {
  fluidPage(
    textInput("txt1", "Enter text1"),
    textInput("txt2", "Enter text2"),
    checkboxInput("caps", "Capitalize"),
    verbatimTextOutput("out1"),
    verbatimTextOutput("out2"),
    
  )
}
server <- function(input, output, session) {
  output$out2<- output$out1 <- renderText({
    if (input$caps)
      paste(toupper(input$txt1), toupper(input$txt2))
    else
      paste(input$txt1, input$txt2)
    
  })
}

shinyApp(ui, server, enableBookmarking = "url")
6yt4nkrj

6yt4nkrj2#

我遇到过类似的情况,需要多个相同的输入(尽管我只需要一个输出),它们总是具有相同的值。
对我来说,解决方案是创建一个电抗元件,它保存输入的值,并将值与输入同步。
即此代码始终使输入1和2具有相同的值

library(shiny)

ui <- fluidPage(
  selectInput("id1", "Input 1", choices = c("A", "B")),
  selectInput("id2", "Input 2", choices = c("A", "B")),
)

server <- function(input, output, session) {
  # the reactive value always holds the value from the inputs
  input_filter <- reactiveVal("A")

  # sync from the reactive value to the inputs
  observeEvent(input_filter(), {
    print("input_filter() has changed")
    updateSelectInput(session, "id1", selected = input_filter())
    updateSelectInput(session, "id2", selected = input_filter())
  })

  # sync from the inputs to the reactive value
  observeEvent(input$id1, {
    print("Update id1")
    input_filter(input$id1)
  })
  observeEvent(input$id2, {
    print("Update id2")
    input_filter(input$id2)
  })
}

shinyApp(ui, server)

相关问题