根据 flexdashboard 中的数据子集绘制简单图表

Plot simple chart on the basis of data subset in 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))
})
```

但是我得到一个错误:试图从一个不是 S4 对象的对象 (class "reactivevalues") 中获取插槽 "selectInput1"

知道哪里做错了吗?以及如何使代码工作?

解决方法如下:

---
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 运行良好。