Loop in R markdown

前端 未结 2 2053
甜味超标
甜味超标 2020-12-07 22:39

I have an R markdown document like this:

The following graph shows a histogram of variable x:

```{r}
hist(x)
```

I want to introduce a loo

相关标签:
2条回答
  • 2020-12-07 23:19

    Could that be what you want?

    ---
    title: "Untitled"
    author: "Author"
    output: html_document
    ---
    
    
    ```{r, results='asis'}
    for (i in 1:2){
       cat('\n')  
       cat("#This is a heading for ", i, "\n") 
       hist(cars[,i])
       cat('\n') 
    }
    ```
    

    This answer was more or less stolen from here.

    0 讨论(0)
  • 2020-12-07 23:26

    As already mentioned, any loop needs to be in a code chunk. It might be easier to to give the histogram a title rather than add a line of text as a header for each one.

    ```{r}
        for i in length(somelist) {
            title <- paste("The following graph shows a histogram of", somelist[[ i ]])
            hist(somelist[[i]], main=title)
        }
    ```
    

    However, if you would like to create multiple reports then check out this thread.

    Which also has a link to this example.
    It seems when the render call is made from within a script, the environmental variables can be passed to the Rmd file.

    So an alternative might be to have your R script:

    for i in length(somelist) {
        rmarkdown::render('./hist_.Rmd',  # file 2
                   output_file =  paste("hist", i, ".html", sep=''), 
                   output_dir = './outputs/')
    }
    

    And then your Rmd chunk would look like:

    ```{r}
        hist(i)
    ```
    

    Disclaimer: I haven't tested this.

    0 讨论(0)
提交回复
热议问题