2017-08-25 61 views
0

我想根據數據子集在flexdashboard中繪製圖表。下面是一個代碼:基於flexdashboard中的數據子集繪製簡單圖表

--- 
title: "Test" 
output: 
    flexdashboard::flex_dashboard: 
    orientation: columns 
    social: menu 
    source_code: embed 
    runtime: shiny 
--- 

```{r global, include=FALSE} 
library(flexdashboard) 
library(ggplot2) 
library(shiny) 

A = c("A1", "A1", "A1", "A2", "A2", "A1", "A2", "A2") 
B = c("B1", "B2", "B1", "B2", "B1", "B2", "B1", "B2") 
x = c(1, 2, 3, 4, 5, 3, 3, 4) 
y = c(5, 4, 3, 2, 1, 5, 3, 4) 
df = data.frame(A, B, x, y, stringsAsFactors = FALSE) 
``` 

Column 
------------------------------- 

### Select options 
```{r} 
selectInput("selectInput1", "Select A:", 
      choices = unique(df$A)) 

selectInput("selectInput2", "Select B:", 
      choices = unique(df$B)) 
``` 

```{r} 
# Create a subset data frame 
selectedData = reactive({ 
    df[df$A == [email protected] & df$B == [email protected], c(3,4)] 
    }) 
``` 

Column 
------------------------------- 

###Chart 

```{r} 
renderPlot({ 
    ggplot(selectedData(), aes(x = x, y = y)) + 
     geom_line() + ggtitle(paste0("Selected ", [email protected], " and ", [email protected])) 
}) 
``` 

但我得到一個錯誤:試圖從一個對象(類「reactivevalues」)獲得槽「selectInput1」這不是一個S4對象

任何想法有做錯了方式?以及如何使代碼工作?

回答

0

這裏是解決方案:

--- 
title: "Test" 
output: 
    flexdashboard::flex_dashboard: 
    orientation: columns 
    social: menu 
    source_code: embed 
    runtime: shiny 
--- 

```{r global, include=FALSE} 
library(flexdashboard) 
library(ggplot2) 
library(shiny) 

A = c("A1", "A1", "A1", "A2", "A2", "A1", "A2", "A2") 
B = c("B1", "B2", "B1", "B2", "B1", "B2", "B1", "B2") 
x = c(1, 2, 3, 4, 5, 3, 3, 4) 
y = c(5, 4, 3, 2, 1, 5, 3, 4) 
df = data.frame(A, B, x, y, stringsAsFactors = FALSE) 
``` 

Column 
------------------------------- 

### Select options 
```{r} 
selectInput("selectInput1", "Select A:", 
      choices = unique(df$A)) 

selectInput("selectInput2", "Select B:", 
      choices = unique(df$B)) 
``` 

```{r} 
# Create a subset data frame 
selectedData = reactive({ 
    df[df$A == input$selectInput1 && df$B == input$selectInput2, c(3,4)] 
    }) 
``` 

Column 
------------------------------- 

###Chart 

```{r} 
renderPlot({ 
    ggplot(selectedData(), aes(x = x, y = y)) + 
     geom_line() + ggtitle(paste0("Selected ", input$selectInput1, " and ", input$selectInput2)) 
}) 
``` 

你做的,而不是使用$@標誌,例如這裏唯一的問題:[email protected]。編輯代碼後 - >將符號更改爲$,flexdashboard完美運行。

+0

非常感謝!如此愚蠢的錯誤......但是,我仍然更喜歡在子集化階段使用「&」而不是「&&」。 – Sergiy