如何从Rmarkdown部分重构Shiny代码的服务器部分

时间:2017-05-29 07:07:22

标签: r shiny refactoring r-markdown flexdashboard

我有以下完全运行Shiny-dashboard App:

---
title: "Test"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    theme: bootstrap
    vertical_layout: scroll
---
```{r setup, include=FALSE}
library(flexdashboard)
library(tidyverse)
```

Basic 
===================================== 

Inputs_basic {.sidebar}
-------------------------------------

```{r io_processes}
 selectInput("mpg_thres", label = "MPG threshold",
              choices = c(10,20,30,40), selected = 10)
 selectInput("cyl_thres", label = "CYL threshold",
              choices = c(4,5,6,7,8), selected = 4)
```

Rows {data-height=500}
-------------------------------------


### Scatter Plot

```{r show_scattr}
mainPanel(

  renderPlot( {
     dat <- as.tibble(mtcars) %>%
            select(mpg, cyl) %>%
            filter(mpg > input$mpg_thres & cyl > input$cyl_thres)
     ggplot(dat, aes(mpg, cyl)) + 
       geom_point()

  })

)
```


Rows  {data-height=500}
-------------------------------------

###  Show verbatim
```{r show_verbatim}
mainPanel(

  renderPrint( {
     dat <- as.tibble(mtcars) %>%
            select(mpg, cyl) %>%
            filter(mpg > input$mpg_thres & cyl > input$cyl_thres)
     dat
  })

)
```

请注意,以下部分代码是多余的 在两个不同的Rmarkdown部分中 Scatter Plot Show verbatim

 dat <- as.tibble(mtcars) %>%
        select(mpg, cyl) %>%
        filter(mpg > input$mpg_thres & cyl > input$cyl_thres)

我如何分解它?

为了完整性,应用程序的屏幕截图如下:

enter image description here

1 个答案:

答案 0 :(得分:5)

使用反应式数据表达式,将输出块更改为:

### Scatter Plot

```{r show_scattr}
dat <- reactive( {
  as.tibble(mtcars) %>%
    select(mpg, cyl) %>%
    filter(mpg > input$mpg_thres & cyl > input$cyl_thres)
} )

mainPanel(
  renderPlot( {
     ggplot(dat(), aes(mpg, cyl)) + 
       geom_point()
  })
)
```

###  Show verbatim
```{r show_verbatim}
mainPanel(
  renderPrint( {
     dat()
  })
)
```

请注意使用reactive以及将dat称为函数(dat())。

reactive确保每次更改输入时都会重新计算dat