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

dubhousing picture dubhousing · Apr 12, 2012 · Viewed 67.2k times · Source

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 rstudio, and I would like to preserve rstudio's formatting when pasting into Word. Principally, I like the font colors and spacing that rstudio uses. I find that when I paste from SAS to Word, the formatting is preserved, but no dice here.

I would usually look for copy special / paste special options to do this, but I can't find any. When I try to paste special into word, only unformatted text options are presented. I would rather not reformat the text line-by-line, because I think it looks pretty nice in rstudio.

I thought of trying to save the script in rstudio to some format that would preserve its formatting, but I couldn't find any way to do this. Does anyone have an idea of how I might pull this off?

Thanks in advance

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Apr 13, 2012

It's not totally clear whether you are pasting from RStudio's script editor (which has some 4 or 5 colors) or from the R console (script + output) within RStudio (which only has 2 colors).

If you are pasting from the console--please check "Paste special" again. There should be an option for "HTML Format" that will do what you need (though you may need to resize the font to make everything fit properly depending on your page margins).

If you are pasting from the script editor, then you're out of luck with a direct copy-and-paste solution. But there is a copy-and-paste-and-copy-and-paste solution...

One solution could be to use Notepad++. From RStudio, save your script (with a ".R" extension) then open the script in Notepad++. (Or copy and paste from RStudio to Notepad++, but make sure you set the file's language--from the "Language" menu--to R). When your script is correctly highlighted in Notepad++ go to the "Plugins > NppExport > Copy HTML to clipboard" menu to copy the open file. This can then be pasted into MS Word with HTML format.