Created
July 26, 2013 12:56
-
-
Save n8thangreen/6088635 to your computer and use it in GitHub Desktop.
Write from R to Word.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| library("R2wd") | |
| require(R2wd) | |
| wdGet(T) # If no word file is open, it will start a new one - can set if to have the file visiable or not | |
| wdNewDoc("H:\\This.doc") # this creates a new file with "this.doc" name | |
| wdApplyTemplate("H:\\This.dot") # this applies a template | |
| wdTitle("Examples of R2wd (a package to write Word documents from R)") # adds a title to the file | |
| wdSection("Example 1 - adding text", newpage = T) # This can also create a header | |
| wdHeading(level = 2, "Header 2") | |
| wdBody("This is the first example we will show") | |
| wdBody("(Notice how, by using two different lines in wdBody, we got two different paragraphs)") | |
| wdBody("(Notice how I can use this: '\ n' (without the space), to \n go to the next | |
| line)") | |
| wdBody("האם זה עובד בעברית ?") | |
| wdBody("It doesn't work with Hebrew...") | |
| wdBody("O.k, let's move to the next page (and the next example)") | |
| wdSection("Example 2 - adding tables", newpage = T) | |
| wdBody("Table using 'format'") | |
| wdTable(format(head(mtcars))) | |
| wdBody("Table without using 'format'") | |
| wdTable(head(mtcars)) | |
| wdSection("Example 3 - adding lm summary", newpage = T) | |
| ## Example from ?lm | |
| ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) | |
| trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) | |
| group <- gl(2,10,20, labels=c("Ctl","Trt")) | |
| weight <- c(ctl, trt) | |
| # This wouldn't work! | |
| # temp <- summary(lm(weight ~ group)) | |
| # wdBody(temp) | |
| # Here is a solution for how to implent the summary.lm output to word | |
| wdBody.anything <- function(output) | |
| { | |
| # This function takes the output of an object and prints it line by line into the word document | |
| # Notice that in many cases you will need to change the text font into courier new roman... | |
| a <- capture.output(output) | |
| for(i in seq_along(a)) | |
| { | |
| wdBody(format(a[i])) | |
| } | |
| } | |
| temp <- summary(lm(weight ~ group)) | |
| wdBody.anything(temp) | |
| wdSection("Example 4 - Inserting some plots", newpage = T) | |
| wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 20) | |
| wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 20) | |
| wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 50) | |
| # wdPageBreak() | |
| wdSave("H:\\This.doc") # save current file (can say what file name to use) | |
| wdQuit() # close the word file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment