Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sweave v. Knitr v. Rmarkdown: code chunk headers

I am trying to understand the relationship between rmarkdown, sweave and knitr. Looking at code and examples I have run into two types of code headers and I don't understand what language/package they belong to.

The headers are

```{}
```

and

<<>>=
@
  1. What is the difference between them?
  2. Ho do they relate to rmarkdown, sweave and knitr?
  3. If I work on a .rnw, which one am I using?
like image 427
Zweifler Avatar asked Nov 10 '18 04:11

Zweifler


1 Answers

Both sweave and rmarkdown provide the ability to run arbitrary code for R, python, and other programming languages. The pros and cons of each are varied, but a quick comparison:

R markdown :

  • typical file extensions: .rmd (case-insens), perhaps .rmarkdown

  • supports R, python, and several other languages

  • outputs to HTML, docx, LaTeX (and therefore PDF), and several other output formats

  • uses the triple-backtick for chunk demarcation

      Regular text.
    
      ```{r chunkname, chunkoptions, ...}
      a <- 1
      ```
    
      ```{python pychunk, chunkoptions, ...}
          def myfun(v: list) -> list:
          """
          Something important in this docstring.
          """
          return [a+1 for a in v]
      ```
    
      More regular text.
    
  • because it is based on markdown, there are some limitations for cross-references, table-control, etc; there are packages and known mitigation techniques for many of them (too many to list here). However, you can use direct LaTeX formatting in the markdown, so output to PDF can enjoy that control as well (though LaTeX code is not translated for other output formats).

Sweave:

  • typical file extensions include .rnw (case-insens) and I've seen .noweb (not fully certain on this ...)

  • supports R, and perhaps other languages if you can get to them through R (such as via reticulate)

  • outputs to LaTeX and therefore PDF

  • uses <<>>= and @ for chunk demarcation:

      Regular text.
    
      <<chunkname, chunkoptions, ...>>=
      a <- 1
      @
    
      More regular text.
    
  • because it is based directly on LaTeX, you can as much control over formatting, cross-referencing, etc

knitr

  • processes files of both sweave and rmarkdown formats
  • some sweave pre-processing may be required (e.g., using Sweave2knitr), ref: https://yihui.name/knitr/demo/sweave/
  • the rationale for knitr is to "solve some long-standing problems in Sweave, and combine features in other add-on packages into one package (knitr ≈ Sweave + cacheSweave + pgfSweave + weaver + animation::saveLatex + R2HTML::RweaveHTML + highlight::HighlightWeaveLatex + 0.2 * brew + 0.1 * SweaveListingUtils + more)."
like image 52
r2evans Avatar answered Nov 13 '22 05:11

r2evans