如何在Rmarkdown演示(slidy)中回显代码之前显示块输出?

时间:2015-09-30 14:57:30

标签: r shiny rstudio r-markdown

我最近开始在Rmarkdown中使用Slidy演示模板,并喜欢每张幻灯片如何向下滚动以获取更多内容。

我使用此方法的一种方法是与学生分享情节(参见下面的示例代码)。在单张幻灯片上,我可以显示绘图以及用于创建绘图的确切代码,可以通过向下滚动来查看。

---
title: Echo Code Chunks After Code Results
subtitle: Thanks For Your Help
author: Me
date: "today"
output: slidy_presentation
runtime: shiny
---

## Slide with Interactive Plot

```{r, echo=TRUE, warning=FALSE, message=FALSE}
shinyApp(options = list(width = "100%", height = "700px"),
  ui = ( fluidPage(
inputPanel(
  selectInput("n_breaks", label = h3("Number of bins:"),
              choices = c(10, 20, 35, 50), selected = 20),

  sliderInput("bw_adjust", label = h3("Bandwidth:"),
              min = 0.2, max = 2, value = 1, step = 0.2)),
    plotOutput("stuff", height = "650px")

)),

server = function(input,output,session) {

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

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

我遇到的问题是默认行为是在代码结果出现之前回显代码块,这与我想要的方式相反。

我显然可以通过插入两个代码块来解决这个问题,其中第一个具有块选项echo=FALSE而第二个具有echo=TRUE, fig.show='hide',但这需要我确保两个代码块匹配。 如何反转此顺序,以便在回显代码之前显示图表。

一如既往,感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您应该能够通过以下内容为演示文稿的主体做您想做的事。

## Slide with Interactive Plot

```{r thecode, echo=FALSE, warning=FALSE, message=FALSE}
shinyApp(options = list(width = "100%", height = "700px"),
  ui = (fluidPage(inputPanel(
    selectInput("n_breaks", label = h3("Number of bins:"), 
                choices = c(10, 20, 35, 50), selected = 20),
    sliderInput("bw_adjust", label = h3("Bandwidth:"), 
                min = 0.2, max = 2, value = 1, step = 0.2)),
    plotOutput("stuff", height = "650px"))),

server = function(input,output,session) {
  output$stuff = renderPlot({
    hist(faithful$eruptions, probability = TRUE, 
         breaks = as.numeric(input$n_breaks), xlab = "Duration (minutes)", 
         main = "Geyser eruption duration", col = "bisque", border = 1)
    dens <- density(faithful$eruptions, adjust = input$bw_adjust, 
                    lwd = 2, col = "blue")
    lines(dens, col = "blue")})
  })
```

```{r thecode, eval=FALSE}
```

那是:

  • 创建两个具有相同名称的代码块(此处为thecode)。
  • 在第一个代码块中,设置echo = FALSE以便代码不会打印出来,但是会对其进行评估。
  • 在第二个代码块中,设置echo = TRUE,但保持块完全为空(围栏之间也没有空行)。