2017-05-29 19 views
3

我有以下的完全運行閃亮的儀表板應用重構的閃亮代碼服務器部分:如何從Rmarkdown部分

--- 
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部分散點圖中劇情逐字顯示

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

我該如何分解它?


爲完整的應用程序的屏幕截圖是這樣的:

enter image description here

回答

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以及作爲函數調用datdat())。

reactive確保每次輸入改變時,dat被重新計算。