Using markdown within code chunks to define large functions

Viewed 208

I would like to use R Markdown on a large project. The project uses a number of very large self-defined functions. I therefore would like to use markdown to comment on certain parts of the function.

```{r}
my_function <- function(x,y){
  test <- x + seq(1,10)
```

Then I would like to use Markdown to describe the second part of the function

```{r}
  output <- test + y
  return(output)
}
```

And then I would like to apply the function

```{r}
my_function(1,2)
```

Of course I realise that I could simply use the # symbol to add a comment, but this is not as nice as markdown. This is relevant e.g. for large shiny server functions or something of the sort. Any ideas how I could do this?

1 Answers

In R-markdown, you cannot define objects (e.g., functions) across chunks (afaict). One alternative would be to define the function invisibly, and then use non-execute code-chunks to talk about the parts. But I don't like that alternative, since it doubles the effort and increases the likelihood of having different functions.

One alternative is to define clear markers in the function, grab the body of the function, and split up by those markers. Try this:

---
title: test markdown
---

```{r echo = FALSE, include = FALSE}
my_function <- function(x,y){
  test <- x + seq(1,10) ###BREAK###
  # normal comment
  output <- test + y    ###BREAK###
  return(output)
}
my_function_body <- strsplit(
  paste(head(capture.output(print.function(my_function)), n = -1), collapse = "\n"),
  "###BREAK###[\n\r]*")[[1]]
```

```{r echo = FALSE, include = TRUE, comment = ''}
cat(my_function_body[[1]])
```

Then I would like to use Markdown to describe the second part of the function


```{r echo = FALSE, include = TRUE, comment = ''}
cat(my_function_body[[2]])
```

Now the third/last part of the function


```{r echo = FALSE, include = TRUE, comment = ''}
cat(my_function_body[[3]])
```

And then I would like to apply the function

```{r}
my_function(1,2)
```

And the whole of the function (excluding the markers):

```{r echo = FALSE, include = TRUE, comment = ''}
cat(
  gsub("###BREAK###", "",
       paste(head(capture.output(print.function(my_function)), n = -1), collapse = "\n"))
)
```

This renders as:

rmarkdown rendered

Related