How to preserve formatting from rstudio when copy/pasting to Word?

前端 未结 7 1897
生来不讨喜
生来不讨喜 2021-01-30 17:11

New to R, Rstudio, and SO -- my apologies in advance for any faux pas.

I want to reproduce my code in Word 2010 for a homework assignment. The scripts were written in r

7条回答
  •  野的像风
    2021-01-30 17:53

    Just in case someone else looks for this question...

    Another way to have all the source code in a word document with a good-looking format using RStudio is to use the File/Compile Notebook option, choosing MS Word as the output format.

    Using this option, a .docx document will be generated with the output of your script as well as the original source code. The script will be executed, though.

    If you don't want your code to be evaluated (you just want a simple copy-paste), you can add #+eval=FALSE at the beginning of your script and then the source code will be reproduced in the word document without being evaluated.

    This approach relies on knitr. Here is an example if anyone wants to start playing with this.

    #' ---
    #' title: "My homework"
    #' author: John Doe
    #' date: June 15, 2015
    #' output: word_document
    #' ---
    
    # The header above sets some metadata used in the knitr output
    
    # Conventional comments are formatted as regular comments
    
    # Comments starting with "#+" control different knitr options.
    
    #+echo=FALSE,message=FALSE,warning=FALSE
    library(ggplot2)
    
    
    #+echo=TRUE
    #' Comments with a "+" sign are used to tell knitr what should be
    #' done with the chunk of code:
    #'
    #'  - echo: Show the original code or not
    #'  - eval: Run the original code or not
    #'  - message: Print messages
    #'  - warning: Print warnings
    #'  - error: Print errors
    #'  ...
    
    #' Comments with an apostrophe "'" will be printed as regular text.
    #' This is very useful to explain what you are actually doing!
    
    # Regular comments can be used to document the code as usual
    # Figures are printed:
    ggplot(mpg, aes(x=cty, y=hwy)) + geom_point(aes(color=class))
    
    #' Formatting **options** are possible.
    #' Even [links](http://stackoverflow.com/questions/10128702/how-to-preserve-formatting-from-rstudio-when-copy-pasting-to-word)
    #'
    
    
    #' This will show all the packages and versions used to generate this document.
    #' It can be used to make sure that your teacher has all he needs to run your script
    #' if he/she wants to.
    sessionInfo()
    

    Word document example

提交回复
热议问题