【问题标题】:How to refactor server part of Shiny code from Rmarkdown sections如何从 Rmarkdown 部分重构 Shiny 代码的服务器部分
【发布时间】:2017-10-29 09:46:19
【问题描述】:

我有以下完全运行的 Shiny-dashboard 应用程序:

---
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)

如何分解?


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

【问题讨论】:

    标签: r shiny refactoring r-markdown flexdashboard


    【解决方案1】:

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

    ### 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-17
      • 2020-12-08
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多