Можно ли отобразить файл «runtime: блестящий» rmarkdown (.rmd) с помощью кнопки действия в блестящем приложении? - PullRequest
1 голос
/ 29 января 2020

Допустим, у нас есть этот "RMD-файл: время выполнения: блестящий", который я построил на RStudio. Он состоит из 4 основных частей:


    ---
    title: "Theory"
    output: html_document
    runtime: shiny
    ---

    Part 1: html code
    <style type="text/css">

    h1.title {

    text-align: center;
    color: DarkBlue;
    font-size: 38px;

    }

    p{

    font-size: 18pt;
    font-family: times, serif;
    }
    </style>


    <br>
    </br>

    ---

    Part2: Inline equations

    <p>
    This is an inline equation: $y = \frac{a}{b}$
    </p>

    <br>
    </br>

    ---

    Part3: Standalone equations

    $$y = \frac{a}{b} $$

    <br>
    </br>

    ---

    Part4: Embedded shiny inputs and outputs

    ```{r eruptions, echo=FALSE}
    inputPanel(
      selectInput("n_breaks", label = "Number of bins:",
                  choices = c(10, 20, 35, 50), selected = 20),

      sliderInput("bw_adjust", label = "Bandwidth adjustment:",
                  min = 0.2, max = 2, value = 1, step = 0.2)
    )

    renderPlot({
      hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
           xlab = "Duration (minutes)", main = "Geyser eruption duration")

      dens <- density(faithful$eruptions, adjust = input$bw_adjust)
      lines(dens, col = "blue")
    })

Я могу «запустить документ», что в rStudio, и он работает отлично.

Теперь я сохраняю этот файл .rmd, а затем ссылаюсь на него позже при создании моего блестящего приложения:


   library(shiny)
ui <- shinyUI(
  fluidPage(
    shinyWidgets::panel(
    fluidRow(
      column(12, align="center",
             actionButton("rmd", "Test")
      )
    ))
#    ,includeHTML(rmarkdown::render("test_rmd.Rmd"))
  )
)

server <- function(input, output) {
                  observeEvent(input$rmd, {
                    output$markdown <- renderUI({
                      includeHTML(rmarkdown::render("test_rmd.Rmd"))
                    })
                  })
}


shinyApp(ui, server) 

Когда я запускаю приложение, оно не может успешно отобразить все 4 части " время выполнения: блестящий "rmd-файл, отличный от самого текста. Причина, по которой я спрашиваю, заключается в том, что я, в конечном счете, хочу создать кнопку действия, которая при нажатии будет отображать файл «время выполнения: блестящий».

Разрешено ли рендеринг? Время выполнения: блестящий «rmd-файлы, потому что они несовместимы с форматом блестящего приложения?

PS Я в основном могу решить эту проблему, преобразовав rmd в html IF часть 4 (« Встроенный блестящий »). входы и выходы ") удаляется (в противном случае я получаю ошибку). Но я хочу сохранить это, если это возможно. Сделал бы мою жизнь намного проще.

Ответы [ 2 ]

1 голос
/ 29 января 2020

Ваш код нуждается в некоторых корректировках (если вы не возражаете).
Самое главное, вам нужно встроить встроенное блестящее приложение (входы и выходы) в .Rmd с помощью shinyApp() function (Part 4):

---
title: "Theory"
output: html_document
runtime: shiny
---

Part 1: hidden css code

```{css part-1, echo = FALSE}
.h1.title {
  text-align: center;
  color: DarkBlue;
  font-size: 38px;
  }

.p{
  font-size: 18pt;
  font-family: times, serif;
  }
```

<br>
</br>

---

Part2: Inline equations

<p>
This is an inline equation: $y = \frac{a}{b}$
</p>

<br>
</br>

---

Part3: Standalone equations

$$y = \frac{a}{b} $$

<br>
</br>

---

Part4: Embedded shiny inputs and outputs

```{r eruptions, echo=FALSE}
shinyApp(
  ui = fluidPage(
    inputPanel(
      selectInput("n_breaks", label = "Number of bins:",
                  choices = c(10, 20, 35, 50), selected = 20),

      sliderInput("bw_adjust", label = "Bandwidth adjustment:",
                  min = 0.2, max = 2, value = 1, step = 0.2)
    ),
    plotOutput("eruptionsPlot")),

    server = function(input, output) {
      output$eruptionsPlot = renderPlot({
      hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
           xlab = "Duration (minutes)", main = "Geyser eruption duration")

      dens <- density(faithful$eruptions, adjust = input$bw_adjust)
      lines(dens, col = "blue")
    })
    },
    options = list(height = "600px")
)
```

Теперь, чтобы отобразить runtime: shiny (или любой другой RMarkdown output: html_document) в блестящем приложении, я бы использовал includeHTML function :

library(shiny)
ui <- shinyUI(
  fluidPage(
    includeHTML(rmarkdown::render("ShinyRMarkdownFile.Rmd"))
  )
)
server <- function(input, output) { }

shinyApp(ui, server) 

С помощью функции includeMarkdown вы можете рендерить только файлы Markdown .md, а с помощью includeHTML вы можете загрузить HTML вывод отрендеренного файла RMarkdown.
Также могут быть другие решения. ...

0 голосов
/ 03 февраля 2020

Хорошо, думаю, я понял это, благодаря Радовану Милети c. Это код, который я использую для файла RMD ("test_rmd.Rmd"):

---
title: "Theory"
output: html_document
runtime: shiny
---


Part 1: hidden css code

<style type="text/css">

h1.title {

text-align: center;
color: DarkBlue;
font-size: 38px;

}

p{

font-size: 18pt;
font-family: times, serif;
}

p1{

font-size: 14pt;
font-family: times, serif;
}

</style>


<br>
</br>

---

Part2: Inline equations

<p>
This is an inline equation: $y = \frac{a}{b}$
</p>

<br>
</br>

---

Part3: Standalone equations

$$y = \frac{a}{b} $$

<br>
</br>

---

Part4: Embedded shiny inputs and outputs

```{r eruptions, echo=FALSE}
shinyApp(
  ui = fluidPage(
    inputPanel(
      selectInput("n_breaks", label = "Number of bins:",
                  choices = c(10, 20, 35, 50), selected = 20),

      sliderInput("bw_adjust", label = "Bandwidth adjustment:",
                  min = 0.2, max = 2, value = 1, step = 0.2)
    ),
    plotOutput("eruptionsPlot")),

    server = function(input, output) {
      output$eruptionsPlot = renderPlot({
      hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
           xlab = "Duration (minutes)", main = "Geyser eruption duration")

      dens <- density(faithful$eruptions, adjust = input$bw_adjust)
      lines(dens, col = "blue")
    })
    },
    options = list(height = "600px")
)
```

Этот код я использую для блестящего приложения:

library(shiny)
library(shinyWidgets)

ui <- shinyUI(
  fluidPage(
    shinyWidgets::panel(
    fluidRow(
      column(12, align="center",
             actionButton("rmd", "Test")
      )
    ))

,uiOutput("test")
  )
)

server <- function(input, output) {
                  observeEvent(input$rmd, {
                    output$test <- renderUI({
                      withMathJax(includeHTML(rmarkdown::render("test_rmd.Rmd")))
                    })
                  })
}


shinyApp(ui, server) 
...