Split function in seperate code chunks in Rmarkdon

Viewed 97

In my script I'm calling a very long function. I would like to include parts of code mixed with markdown from within the function. I don't know how I can split a function into seperate code chuncks and markdown.

In the example below I have a function getres(). I would like to display this function as I displayed it below the "What I want"-header. Is there a way?


    ---
    title: "Example"
    output: html_document
    ---
    ## What I have now:
    
    ```{r desiref}
    getRes <- function(){
      # Here I'm calculating 1+1:
      res<- 1+1
      # Here I'm multiplying the resuls by two:
      res<- res*2
      return(res)
    }
    res<-getRes()
    ```
    
    The results is: `r res`
    
    ## What I want:
    
    Here I'm calculating 1+1:
    
    ```{r ex1}
    res <- 1+1
    ```
    
    Here I'm multiplying the resuls by two:
    
    ```{r ex2}
    res<- res*2
    ```
    
    The results is: `r res`

Which gives the markdown:

What I have now:

    getRes <- function(){
      # Here I'm calculating 1+1:
      res<- 1+1
      # Here I'm multiplying the resuls by two:
      res<- res*2
      return(res)
    }
    res<-getRes()

The results is: r res

What I want:

Here I'm calculating 1+1:

    res <- 1+1

Here I'm multiplying the resuls by two:

    res<- res*2

The results is: r res

1 Answers

This might actually have been solved in this question: How do I explain a complicated function in Rmarkdown?

The answer is (I added an extra argument to check if the function works properly):


    ---
    title: "Example"
    output: html_document
    ---
    ## Old function:
    
    ```{r desiref, echo=FALSE}
    getRes <- function(){
      # Here I'm calculating 1+1:
      res<- 1+1
      # Here I'm multiplying the resuls by two:
      res<- res*2
      return(res)
    }
    res<-getRes()
    ```
    ## Answer :

    Here I'm calculating 1+1:
    ```{r Xsquare1, eval=F}
    res<- 1+x
    ```
    
    Here I'm multiplying the resuls by two:
    ```{r Xsquare2, eval=F}
    res<- res*2
    ```
    
    
    ```{r complicated, eval=T, echo=FALSE}
    complicated = function(x) {
       <<Xsquare1>>
       <<Xsquare2>>
    }
    res=complicated(5)
    ```
    The results is: `r res`
    
    ## Old requirement:
    
    Here I'm calculating 1+1:
    
    ```{r ex1}
    res <- 1+1
    ```
    
    
    Here I'm multiplying the resuls by two:
    
    ```{r ex2}
    res<- res*2
    ```
    
    The results is: `r res`

Related