kathystehl
kathystehl

Reputation: 841

Stop R Markdown from adding breaks between code and output

I'm creating an HTML page from R Markdown with the following .rmd code:

---
title: 'TITLE'
author: "NAME"
date: "DATE"
output: 
  html_document: 
    keep_md: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
(n1 <- nrow(perf))  # Save the number of rows in 'perf'
(m1 <- ncol(perf))  # Save the number of columns in 'perf'
```

When I knit my page, it returns my code and output in separate chunks, but I would like them to all be included in a single chunk, embedded in my .md. The result looks like this:

Screen shot of .md output

But, I would like the spaces between the sections to disappear, and the code and output all be included in a single section. Is this possible?

I am planning on putting this on GitHub, so if there's anyway to make this work for a GitHub-specific markdown would be helpful (I know that's not how I have the .md currently configured, but that's my next step).

Upvotes: 1

Views: 956

Answers (2)

kathystehl
kathystehl

Reputation: 841

Very simply, include the specification collapse = TRUE in specification for the chunk of code in the .rmd file:

```{r, collapse = TRUE}
(n1 <- nrow(perf))  # Save the number of rows in 'perf'
(m1 <- ncol(perf))  # Save the number of columns in 'perf'
```

Upvotes: 4

Martin Schmelzer
Martin Schmelzer

Reputation: 23899

I have two possible solutions for you:

1. Combine each source code chunk with the following output chunk

You could try to add the following JavaScript chunk in your RMarkdown script:

<script>
$chunks = $('pre.r');
$chunks.each(function() {
    if ($(this).next().is('pre:not(r)')) {
        var newc = '<br>' + $(this).next('pre').children('code').html();
        var oldc = $(this).children('code').html();
        $(this).children('code').html(oldc.concat(newc));
        $(this).next('pre').remove();
    }
})
</script>

enter image description here

2. Put everything that belongs to one R-chunk into one box

Or if you want all html chunks that belong to the same RMarkdown chunk in one box try

<script>
$chunks = $('pre.r');
$chunks.each(function() {
    while($(this).next().is('pre')) {
        var newc = '<br>' + $(this).next('pre').children('code').html();
        var oldc = $(this).children('code').html();
        $(this).children('code').html(oldc.concat(newc));
        $(this).next('pre').remove();
    }
})
</script>

enter image description here

Upvotes: 0

Related Questions