Putting function definition after call in R knitr -


quick, , stupid, question: in r markdown/knitr document, possible put function definition @ end of doc (e.g. in appendix) after function called?

is possible put function definition @ end of document, after function called?

technically, no. function needs defined before called. however, question relates knitr should rephrased:

is possible show function definition @ end of document, after function called?

yes, , there several ways achieve this. note options 2 , 3 can found in print highlighted source code of function.

option 1: reuse chunks

define function before used.

```{r definition, echo = false} myfun <- function(x) {   return(sprintf("you passed me %s", x)) } ```  use function: ```{r} myfun(123) ```  show chunk defined: ```{r definition, eval = false} ``` 

an empty chunk same label non-empty chunk "inherits" latter's code. described in how reuse chunks. code inside chunk definition hidden @ first (echo = false). later, when code printed, use eval = false in order avoid evaluating code again.

this option handy when function defined in separate chunk.

option 2: simple print

this simplest option output won't have syntax highlighting. define function in hidden chunk, use , print function definition later:

define function *before* used.  ```{r definition, echo = false} myfun <- function(x) {   return(sprintf("you passed me %s", x)) } ```  use function:   ```{r} myfun(123) ```   ```{r} myfun ``` 

option 3: generate chunk containing function definition

this option described on yihui's website. uses function insert_fun generate chunk contains function definition.

insert_fun = function(name) {   read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-')) } 

this approach flexible because doesn't matter if function defined in separate chunk or in file sourced.

insert_fun takes name of function (as character) , creates chunk labelled functionname-source:

define function *before* used.  ```{r definition, echo = false}  # define function.  myfun <- function(x) {    return(sprintf("you passed me %s", x)) }  library(knitr)  # define insert_fun. insert_fun = function(name) {   read_chunk(lines = capture.output(dump(name, '')), labels = paste(name, 'source', sep = '-')) }  insert_fun("myfun") # creates chunk labelled "myfun-source" ```  use function:   ```{r} myfun(123) ```   ```{r myfun-source, eval = false} ``` 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -