2017-08-25 60 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