首页 > 解决方案 > Rmarkdon中单独代码块中的拆分功能

问题描述

在我的脚本中,我调用了一个很长的函数。我想在函数中包含与降价混合的部分代码。我不知道如何将函数拆分为单独的代码块和降价。

在下面的示例中,我有一个函数 getres()。我想在“我想要的”标题下方显示此功能。有办法吗?


    ---
    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`

这给出了降价:

我现在拥有的:

    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()

结果是:r res

我想要的是:

这里我计算 1+1:

    res <- 1+1

在这里,我将结果乘以 2:

    res<- res*2

结果是:r res

标签: rr-markdown

解决方案


这实际上可能已经在这个问题中得到了解决: 如何在 Rmarkdown 中解释一个复杂的函数?

答案是(我添加了一个额外的参数来检查函数是否正常工作):


    ---
    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`


推荐阅读