Tuesday, August 05, 2014

How to generate a color-coded/formatted Word file of R programs in RStudio

RMarkdown: Generate a color-coded/formatted Word file of R! using RStudio

Here is my approaches/cheat-sheet/template:

If have codes like these:
 
     library("xxx")    
     summary (usmort)
 
Method I (using RStudio)
  • Start a new R markdown file (File -> New File-> R Markdown).
  • Delete all the codes that RStudio generated in that new file.
  • Copy and paste the R codes above into the new file
  • Add global option (between --- and ---), chunk head (```) with option (eval=FALSE), and chunk tail (```) :
    ---
    output:
    word_document:
    highlight: pygments
    ---
    ```{r,eval=FALSE}
                 ... your codes here ...
    ``` 
  • Click the ‘knit word’ button, you get a Word file with codes show like below: 
     library("xxx")
     summary
(usmort)
 
Method II (with or without using RStudio)
  • add chunk head (```{r,eval=FALSE}) and tail (``` ) and wrap the whole codes, and save the file ("xxx_r_code.R").
  • run the R commands in console window:
       >library(rmarkdown)
    >render("xxx_r_codes.R",word_document(highlight="pygments"))

No comments: