在flexdashboard中基于数据子集绘制简单图表

时间:2017-08-25 17:54:26

标签: r 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 == 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))
})
```

但是我收到了一个错误:尝试获取插槽" selectInput1"来自不是S4对象的对象(类"反应值")

任何想法以错误的方式做了什么?以及如何使代码工作?

1 个答案:

答案 0 :(得分: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))
})
```

您遇到的唯一问题是使用@符号代替$,例如:input@selectInput1。编辑代码后 - >将标志更改为$,flexdashboard完美运行。