2017-06-16 73 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 
    } 
})