R selectInput反应性问题

时间:2017-06-16 14:14:43

标签: r shiny shiny-reactivity

我在Shiny中遇到反应问题。在我的用户界面中,我有

library(tidyverse)
library(shiny)
library(forcats)

ui <- fluidPage(

  titlePanel(h1("Percent Cover")),

  selectInput("selectInput", "Select Site", choices = c("A", "B", "C", "D")), 


plotOutput("coverTypeBarChart", height = "600px")

)

这些对应于我在服务器顶部读入的数据帧A,B,C,D。

在我的服务器中,我有:

 colors <- c("red", "blue", "green", "purple")



reactive({

    if (input$selectInput == "A")
    {data <- A}
    else if (input$selectInput == "B")
    {data <- B}
    else if (input$selectInput == "C")
    {data <- C}
    else if (input$selectInput == "D")
    {data <- D}

 })


    data() <- na.omit(as.data.frame(data()$cover_group))
  names(data()) <- c("tmp")

  cover_group_factor <- as.factor(data()$tmp)

 cover_group_factor <-  fct_recode(cover_group_factor, OTHER = "E", OTHER = "F", OTHER = "G", OTHER = "H", OTHER = "I", OTHER = "J", OTHER = "K")

    bar <- ggplot(data = data()) +
            geom_bar(mapping = aes(x = cover_group_factor, y = ..count../sum(..count..)), fill = colors) + xlab("Cover Group") + ylab("Percent")




 observe({
   output$coverTypeBarChart <- renderPlot(bar)
        })

} 

我知道当我手动将数据分配给任何值,并手动运行代码时,我可以生成该图,所以我知道这是一个反应性问题。

感谢。

2 个答案:

答案 0 :(得分:1)

我最近不得不解决类似的问题。对于以下示例,我编写了一些数据:

library(shiny)
library(ggplot2)

set.seed(1)
A <- sample_frac(mtcars,0.2) %>% select(cyl)
B <- sample_frac(mtcars,0.2) %>% select(cyl)
C <- sample_frac(mtcars,0.2) %>% select(cyl)
D <- sample_frac(mtcars,0.2) %>% select(cyl)

以下是ui的最简单版本,其中包含inputoutput

ui <- fluidPage(
          selectInput("choice", "Select Site", choices = c("A", "B", "C", "D")), 
          plotOutput("barchart", height = "600px")
      )

我使用的技巧是name使用get检索所需的data.frame。例如:

get("A")

                 cyl
Merc 230           4
Merc 450SE         8
Fiat 128           4
Porsche 914-2      4
Valiant            6
Pontiac Firebird   8

server

的背景下
server <- function( input, output ) {
               output$barchart <- renderPlot(ggplot(data = get(input$choice), aes(cyl)) + geom_bar())
          }

正如您在上面的ggplot声明中所看到的,我正在使用input$choice检索get提供的数据。

答案 1 :(得分:0)

我同意p0bs - 您需要将reactive表达式的结果分配给变量。

此外,嵌套的if...else语句具有特定的语法。 else必须与if语句的结束括号位于同一行。

这可能有用:

data <- reactive({
    if(input$selectInput == "A"){
        A
    } else if(input$selectInput == "B") {
        B
    } else if(input$selectInput == "C") {
        C
    } else if(input$selectInput == "D") {
        D
    }
})
相关问题