2017-06-16 75 views
1

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

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") 

) 

这些对应于dataframes 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) 
     }) 

} 

我知道当我手动分配数据给任何值,并手动运行的代码,我可以生产的情节,所以我知道这是一个反应性的问题。

谢谢。

+0

我不能说太多,因为我没有数据框架的例子。但是,从我看到的情况来看,我看不到您已将任何东西附加到您的反应函数中。难道你需要说以下吗? '数据< - 反应({ 如果(输入$ selectInput == “A”) {数据< - A} 否则如果(输入$ selectInput == “B”) {数据< - B} 如果(输入$ selectInput ==“C”) { – p0bs

回答

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") 
    ) 

我使用的技巧是检索数据。你想要的框架nameget。例如:

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上述声明,我检索使用getinput$choice给出的数据看。

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 
    } 
})